Python 为文本的标记和标记创建字典
我有一个标记的文本,我想做一个标记和文本标记的字典。 我试过这个Python 为文本的标记和标记创建字典,python,python-2.7,python-3.x,dictionary,Python,Python 2.7,Python 3.x,Dictionary,我有一个标记的文本,我想做一个标记和文本标记的字典。 我试过这个 text = "he/s is/v a/p good/j man/n" dic = {} for w in text.split(): ti = w.split('/') tok =ti[0] tag =ti[1] dic[tok] = tag print dic 这是输出 {'he': 's'} {'is': 'v', 'he': 's'} {'a': 'p', 'is': 'v',
text = "he/s is/v a/p good/j man/n"
dic = {}
for w in text.split():
ti = w.split('/')
tok =ti[0]
tag =ti[1]
dic[tok] = tag
print dic
这是输出
{'he': 's'}
{'is': 'v', 'he': 's'}
{'a': 'p', 'is': 'v', 'he': 's'}
{'a': 'p', 'is': 'v', 'good': 'j', 'he': 's'}
{'a': 'p', 'is': 'v', 'good': 'j', 'man': 'n', 'he': 's'}
如何防止重复这是因为您在for循环中打印,您可以通过列表理解来完成所有操作。首先按空格s拆分字符串。然后按/:
您没有创建任何重复项。只需将print语句放在for循环的外部,而不是内部,如下所示:
for w in text.split():
ti = w.split('/')
tok =ti[0]
tag =ti[1]
dic[tok] = tag
print dic
输出将是:
{'a': 'p', 'is': 'v', 'good': 'j', 'man': 'n', 'he': 's'}
您可以通过以下简单方式创建此词典:
>>> text = "he/s is/v a/p good/j man/n"
>>> dict([i.split('/') for i in text.split()])
{'a': 'p', 'is': 'v', 'good': 'j', 'man': 'n', 'he': 's'}
为什么不按文本的顺序排列呢?这是因为python字典是无序的数据结构。字典中不需要顺序,因为任何值都可以通过其键直接访问。
>>> text = "he/s is/v a/p good/j man/n"
>>> dict([i.split('/') for i in text.split()])
{'a': 'p', 'is': 'v', 'good': 'j', 'man': 'n', 'he': 's'}