2014-11-05 55 views
-1

我要帶字的數組,然後轉換成一串整數,這樣一些獨特的整數k對應於一些獨特的字j是否可以將整數分配給Python中的單詞?

例子:

一句話:"The cat sat on the mat"
數字格式:1 2 3 4 1 5

在Python,如果讓我怎麼去做這可能嗎?

+1

是;找到一個教程,並閱讀有關字典。 – jonrsharpe 2014-11-05 22:37:49

回答

4

你可以用一個計數器和一個字典做到這一點:

index = 1 
word_to_index = {} 
for word in sentence.split(): 
    if word in word_to_index: 
     # already seen 
     continue 
    word_to_index[word.lower()] = index 
    index += 1 

此分配一個唯一的每個索引(小寫)字;現在你可以使用這些輸出的數字:

print sentence 
for word in sentence.split(): 
    print word_to_index[word.lower()], 

如果你想使用一些Python標準庫魔法,使用collections.defaultdict() object結合itertools.count()

from collections import defaultdict 
from itertools import count 

word_to_index = defaultdict(count(1).next) 

print sentence 
for word in sentence.split(): 
    print word_to_index[word.lower()], 

對於Python 3,你會必須使用count(1).__next__,以及更明顯的開關使用print()作爲函數(print(word_to_index[word.lower()], end=' '))。

這將自動生成指數每個字。後一種方法的演示:

>>> from collections import defaultdict 
>>> from itertools import count 
>>> sentence = "The cat sat on the mat" 
>>> word_to_index = defaultdict(count(1).next) 
>>> print sentence 
The cat sat on the mat 
>>> for word in sentence.split(): 
...  print word_to_index[word.lower()], 
... 
1 2 3 4 1 5 
0

您可以通過獨特的單詞列表中的一句話,然後通過文字,即可在句子單詞去和查找每個單詞的在列表中的位置做到這一點。

sentence = "The cat sat on the mat" 
words_in_sentence = sentence.lower().split() 
unique_words = list(set(words_in_sentence)) 
print [unique_words.index(word) for word in words_in_sentence] 
1
import collections 
import itertools 

c = itertools.count() 
answer = collections.defaultdict(c.__next__) 
for word in sentence.lower().split(): 
    answer[word] 

輸出:

In [29]: answer 
Out[29]: defaultdict(<method-wrapper '__next__' of itertools.count object at 0x10a420c08>, {'mat': 4, 'sat': 2, 'the': 0, 'on': 3, 'cat': 1}) 

要打印出指數:

for word in sentence.lower().split(): 
    print(answer[word], end=' ') 

輸出:

0 1 2 3 0 4 

湊RSE,你可以使指數在1開始通過更改默認參數itertools.countitertools.count(1)

相關問題