2016-07-05 72 views
2

我需要查找用戶輸入的句子中單詞的位置,並且如果該單詞出現多次,只會首次打印該單詞出現的單詞查找單詞出現多次的句子中的原始位置

我有代碼,以便遠

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) 

但它打印的句子中各個單詞的位置,而不是重複出現不止一次

任何一個字的原始位置幫我這個?

+1

你的問題不清楚;也許一個或兩個例子會有所幫助。 –

回答

2

如果您使用的是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) 

基本上採用全nonalphanumerics(逗號,冒號,等等)上的分裂。請注意,您可以通過這種方式獲得空白條目(可能在最後)。

+0

'raw_input'在python3中被刪除。 – Arnial

+0

@Arnial啊,我還在用2.7。我會更新。不久的一天,我會與時俱進。謝謝:-) – woot

+0

@woot,我想OP需要一個類似於我答案中的輸出。 >>> *但它會打印句子中單個單詞的位置,而不是重複出現一次以上單詞的原始位置*。你怎麼看? – SilentMonk

1

你的代碼需要進行一些修改,以達到你正在嘗試做的事:

  • if words.count(a)>2:這應該是if words.count(a)>1,因爲如果重複字數將超過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] 
0

分割字符串

>>> 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)] 
>>> 
相關問題