簡體   English   中英

如何在字符串中查找重復單詞的位置-Python

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM