简体   繁体   English

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

[英]How to find the position of a repeating word in a string - Python

How to get Python to return the position of a repeating word in a string? 如何使Python返回字符串中重复单词的位置?

Eg the word "cat" in "the cat sat on the mat which was below the cat" is in the 2nd and 11th position in the sentence. 例如,“猫坐在猫下面的垫子上”中的“猫”一词在句子的第2位和第11位。

You can use re.finditer to find all occurrences of the word in a string and starting indexes: 您可以使用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)

And using dictionary comprehension: 并使用字典理解:

{word: [w.start() for w in re.finditer(word, sentence)] for word in sentence.split()}

This will return a dictionary mapping each word in the sentence, which repeates at least once, to the list of word index (not character index) 这将返回一个字典,该字典将句子中的每个单词(至少重复一次)映射到单词索引(不是字符索引)列表

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)

The following will take an input sentence, take a word from the sentence, and then print the position(s) of the word in a list with a starting index of 1 (it looks like that's what you want from your code). 下面的代码将输入一个句子,从该句子中取出一个单词,然后将其在列表中的位置打印,索引的起始索引为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)

I prefer simplicity and here is my code below: 我更喜欢简单,这是下面的代码:

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)

The 'words' consists of the list of all the words present in the sentence. “单词”由句子中所有单词的列表组成。 Then after that, we iterate and match each word present at index 'pos' with the word we are looking to find(word_to_find) and if both the words are same then we print the value of pos with 1 added to it. 然后在那之后,我们迭代并找到索引“ pos”中存在的每个单词与我们要查找的单词(word_to_find)匹配,如果两个单词都相同,则我们打印pos的值并添加1。

Hope this is simple enough for you to understand and it serves your purpose. 希望这对您来说足够简单,并且可以满足您的目的。

If you wish to use a list comprehension for the above, then: 如果您希望对以上内容使用列表理解,则:

words = sentence.split()
positions = [ i+1 for i in range(len(words)) if word_to_find == words[i]]
print (positions)

Both the above ways are same, just the later gives you a list. 上面的两种方法都是相同的,只是后面的方法会列出您的列表。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM