[英]In python, how do I find the positions of a word that occurs more than once in a sentence using a for loop?
[英]Finding the original positions of words in a sentence when the word occurs more than once
我需要找到用戶輸入的句子中單詞的位置,如果單詞出現多次,請僅在單詞首次出現時打印
到目前為止,我已經有了代碼-
sentence=input("Enter a sentence: ")
sentence=sentence.lower()
words=sentence.split()
place=[]
for c,a in enumerate(words):
if words.count(a)>2 :
place.append(words.index(a+1))
else:
place.append(c+1)
print(sentence)
print(place)
但是它會打印句子中各個單詞的位置,而不是重復出現多次的單詞的原始位置
誰能幫我這個???
如果您使用的是python 2,則將用raw_input
代替input
否則它將生效。 那不是問題,只是一個觀察(然后您可能正在使用python 3,所以我將其保留)。
您可以創建字典來跟蹤找到的字數和位置。 這基本上是列表的命令。 字典是單詞到位置列表的映射。
sentence=input("Enter a sentence: ")
sentence=sentence.lower()
words=sentence.split()
place={}
for pos, word in enumerate(words):
try:
place[word].append(pos)
except KeyError:
place[word] = [pos]
print(sentence)
print(place)
另外,如果您想在句子解析方面做一些更高級的操作,則可以執行以下操作:
import re
words = re.split('\W+',sentence)
基本上使用所有非字母數字(逗號,冒號等)作為拆分。 請注意,您可以通過這種方式獲得一個空白條目(可能在最后)。
您的代碼需要進行一些修改才能實現您要執行的操作:
if words.count(a)>2
:應該是if words.count(a)>1
因為如果重復單詞,count會大於1。
place.append(words.index(a+1))
:它應該是place.append(words.index(a)+1)
因為您要查找a的索引,然后將其添加1。
根據建議修改的代碼:
sentence=input("Enter a sentence: ")
sentence=sentence.lower()
words=sentence.split()
place=[]
for c,a in enumerate(words):
if words.count(a)>1 :
place.append(words.index(a)+1)
else:
place.append(c+1)
print(sentence)
print(place)
輸出:
Enter a sentence: "hello world hello people hello everyone" hello world hello people hello everyone [1, 2, 1, 4, 1, 6]
分割字符串
>>> s = '''and but far and so la ti but'''
>>> s = s.split()
>>> s
['and', 'but', 'far', 'and', 'so', 'la', 'ti', 'but']
使用set
查找唯一單詞,並使用list.index
方法查找每個唯一單詞的第一個位置。
>>> map(s.index, set(s))
[0, 5, 2, 1, 4, 6]
將結果與唯一的單詞zip
在一起,以使單詞與其位置相關聯。
>>> zip(set(s),map(s.index, set(s)))
[('and', 0), ('la', 5), ('far', 2), ('but', 1), ('so', 4), ('ti', 6)]
>>>
我認為列表理解可能更容易閱讀;
>>> s = '''and but far and so la ti but'''
>>> s = s.split()
>>> result = [(word, s.index(word)) for word in set(s)]
>>> result
[('and', 0), ('la', 5), ('far', 2), ('but', 1), ('so', 4), ('ti', 6)]
>>>
按位置排序
>>> import operator
>>> position = operator.itemgetter(1)
>>> result.sort(key = position)
>>> result
[('and', 0), ('but', 1), ('far', 2), ('so', 4), ('la', 5), ('ti', 6)]
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.