我要带字的数组,然后转换成一串整数,这样一些独特的整数k
对应于一些独特的字j
。是否可以将整数分配给Python中的单词?
例子:
一句话:"The cat sat on the mat"
数字格式:1 2 3 4 1 5
在Python,如果让我怎么去做这可能吗?
我要带字的数组,然后转换成一串整数,这样一些独特的整数k
对应于一些独特的字j
。是否可以将整数分配给Python中的单词?
例子:
一句话:"The cat sat on the mat"
数字格式:1 2 3 4 1 5
在Python,如果让我怎么去做这可能吗?
你可以用一个计数器和一个字典做到这一点:
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
您可以通过独特的单词列表中的一句话,然后通过文字,即可在句子单词去和查找每个单词的在列表中的位置做到这一点。
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]
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.count
:itertools.count(1)
是;找到一个教程,并阅读有关字典。 – jonrsharpe 2014-11-05 22:37:49