2015-12-04 28 views
-1

我需要接受一個句子。找出該句子中的所有單詞。然後找出句子中每個單詞的位置。例如,製作一個.txt文檔,其中包含所有單詞及其位置。字符串中所有單詞的位置

Sentence=some people dont like coding but some people do like coding. 
Words=some people dont like coding but do 
Position = 1,2,3,4,5,6,1,2,6,4,5 

但是文字和數字需要在文檔中輸出。

任何想法?

更新:我現在有這個。

sentence= input("Enter a sentence") 
words=sentence.split (" ") 
for (i, subword) in enumerate(words): 
    print (i+1) 

但是,如果這個詞被重複,它將它視爲同一個詞。

+1

任何嘗試?..... –

+0

有很多想法。你是否嘗試過自己研究它們中的任何一個?例如,[官方Python教程](https://docs.python.org/3.4/tutorial/index.html)告訴你如何直接或通過提供建築物來做很多你想要的事情塊。 – TigerhawkT3

+0

謝謝我會看看 – Peter

回答

0

您必須在容器中保留與他們的等級相匹配的獨特單詞。如果性能是一個問題,你可以在collections模塊中使用OrderedDict,或者根據數值簡單地使用一個字典,並在最後對其進行排序(鍵值爲單詞,值爲等級)。

然後,您迭代初始列表,查看是否在唯一字容器中的單詞。如果不是,則將其添加到容器中,然後在任何情況下將排名存儲到位置列表中。

下面是使用列表作爲唯一字容器的簡單實現(名單自動給出的排名與index法):

words = sentence.split(" ") 
uniqwords = [] 
position = [] 
for word in words: 
    if word in uniqwords: 
     position.append(uniqwords.index(word) + 1) 
    else: 
     uniqwords.append(word) 
     position.append(len(uniqwords)) # index of a newly appended elt is len - 1 ... 
0

我會告訴你一些示例代碼,可以幫助你。而且還需要對句子進行一些預處理,例如按',','。',':'等分割句子。 簡單的代碼如下:

Sentence='some people dont like coding but some people do like coding' 
sentList = Sentence.split(' ') 
position = [word.index(x)+1 for x in sentList] 

的結果是這樣的:

In [18]: print(position) 
[1, 2, 3, 4, 5, 6, 1, 2, 7, 4, 5] 

我希望它可以幫助你。

+0

[word.index(x)+1 for x in sentList]這個代碼比循環的性能高得多。 –

相關問題