使用单词重复查找字符串中单词的位置

时间:2015-10-15 16:30:17

标签: python

这是我的代码:

$sql = sprintf("SELECT COUNT(*) as qty FROM users WHERE email= '%s' and password = '%s'", mysql_real_escape_string($_POST['email']), mysql_real_escape_string($_POST['password']));
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);

if ($row['qty']) {...

是的,所以这就是我所拥有的,但如果这个词重复,那么它只显示第一个位置。有什么想法吗?

4 个答案:

答案 0 :(得分:2)

试试这个:

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
for (i, subword) in enumerate(words):
    if (subword == keyword): 
        print(i+1)

答案 1 :(得分:0)

one liner with Counter

from collections import Counter
import re

s = "A sunny day, or rainy day"
# first split. Counter will find frequencies. most_common(1) will
# find repeating word and its frequency (2 in this case). 
# [0][0] will extract the word from Counter tuple, and put it into rindex
# as argument. 
print(s.rindex(Counter(re.split(r'[ ,]',s)).most_common(1)[0][0]))

22

答案 2 :(得分:0)

这是一个更简单的版本,更接近原始风格。

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')

for i, word in enumerate(words):
    if keyword == word:
        print(i+1)  # if you want the index to start at 1, not 0

Python enumerate函数返回单词的索引以及单词本身。

答案 3 :(得分:-1)

这是如何执行代码,但如果句子中没有单词,则会在末尾显示错误消息

 sentence= input("Please Enter A Sentence With No Puncatuation:> ")
 sentence= sentence.lower()
 keyword= input("Please Input A Word From The Sentence:> ")
 keyword= keyword.lower()
 words= sentence.split(' ')
 for (i, subword) in enumerate(words):
     if(subword == keyword):
        print(i+1)
        break
 else:
     print("Error This Word Isnt In The Sentence")

此代码也是不敏感的,所以你可以做任何案例