如何在字符串中找到重复单词的位置 - Python

时间:2016-02-04 19:05:17

标签: python

如何让Python返回字符串中重复单词的位置?

E.g。 “猫坐在猫下面的垫子上”中的“猫”这个词在句子的第2和第11位。

6 个答案:

答案 0 :(得分:2)

您可以使用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()}

答案 1 :(得分:1)

这将返回一个字典,将句子中的每个单词(至少重复一次)映射到单词索引列表(不是字符索引)

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)

答案 2 :(得分:0)

以下将采用输入句子,从句子中取出一个单词,然后在起始索引为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)

答案 3 :(得分:0)

我更喜欢简单,下面是我的代码:

convert.exe -page A4 test.png xc:white -gravity center -composite -format pdf -resize "595x842>" test.pdf

''由句子中出现的所有单词列表组成。然后,我们迭代并匹配索引' pos'中出现的每个单词。用我们想要查找的单词(word_to_find),如果两个单词相同,那么我们打印pos的值,加上1。

希望这很简单,让你理解,它符合你的目的。

如果您希望使用上面的列表理解,那么:

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)

上述两种方式都相同,只是后面会给你一个清单。

答案 4 :(得分:0)

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)

答案 5 :(得分:-1)

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)