[英]How to find the position of a repeating word in a string - Python
如何使Python返回字符串中重复单词的位置?
例如,“猫坐在猫下面的垫子上”中的“猫”一词在句子的第2位和第11位。
您可以使用re.finditer
查找字符串中所有出现的单词并以索引开头:
import re
for word in set(sentence.split()):
indexes = [w.start() for w in re.finditer(word, sentence)]
print(word, len(indexes), indexes)
并使用字典理解:
{word: [w.start() for w in re.finditer(word, sentence)] for word in sentence.split()}
这将返回一个字典,该字典将句子中的每个单词(至少重复一次)映射到单词索引(不是字符索引)列表
from collections import defaultdict
sentence = "the cat sat on the mat which was below the cat"
def foo(mystr):
sentence = mystr.lower().split()
counter = defaultdict(list)
for i in range(len(sentence)):
counter[sentence[i]].append(i+1)
new_dict = {}
for k, v in counter.iteritems():
if len(v) > 1:
new_dict[k] = v
return new_dict
print foo(sentence)
下面的代码将输入一个句子,从该句子中取出一个单词,然后将其在列表中的位置打印,索引的起始索引为1(这就是您想要的代码)。
sentence = input("Enter a sentence, ").lower()
word = input("Enter a word from the sentence, ").lower()
words = sentence.split(' ')
positions = [ i+1 for i,w in enumerate(words) if w == word ]
print(positions)
我更喜欢简单,这是下面的代码:
sentence = input("Enter a sentence, ").lower()
word_to_find = input("Enter a word from the sentence, ").lower()
words = sentence.split() ## Splits the string 'sentence' and returns a list of words in it. Split() method splits on default delimiters.
for pos in range(len(words)):
if word_to_find == words[pos]: ## words[pos] corresponds to the word present in the 'words' list at 'pos' index position.
print (pos+1)
“单词”由句子中所有单词的列表组成。 然后在那之后,我们迭代并找到索引“ pos”中存在的每个单词与我们要查找的单词(word_to_find)匹配,如果两个单词都相同,则我们打印pos的值并添加1。
希望这对您来说足够简单,并且可以满足您的目的。
如果您希望对以上内容使用列表理解,则:
words = sentence.split()
positions = [ i+1 for i in range(len(words)) if word_to_find == words[i]]
print (positions)
上面的两种方法都是相同的,只是后面的方法会列出您的列表。
positions= []
sentence= input("Enter the sentence please: ").lower()
sentence=sentence.split( )
length=len(sentence))
word = input("Enter the word that you would like to search for please: ").lower()
if word not in sentence:
print ("Error, '"+word+"' is not in this sentence.")
else:
for x in range(0,length):
if sentence[x]==word: #
positions.append(x+1)
print(word,"is at positions", positions)
s="hello fattie i'm a fattie too"
#this code is unsure but manageable
looking word= "fattie"
li=[]
for i in range(len(s)):
if s.startswith(lw, i):
print (i)
space = s[:i].count(" ")
hello = space+1
print (hello)
li.append(hello)
print(li)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.