在python 3中创建一个由单词索引组成的字典

时间:2013-07-04 11:56:51

标签: python python-3.x

输入:字符串列表['who are they','are you there?','Yes! you be there']

输出:一个字典,用于将任何字符串中的每个单词映射到由该字符串组成的集合             包含单词的所有字符串的id。

output = {'who':[1], 'are':[1,2], 'they':[1], 'you':[2,3], 'there':[2], 'Yes':[3], 'be':[3]}

我被困了请求帮助,我无法制作执行此功能的方法或程序。

3 个答案:

答案 0 :(得分:7)

使用collections.defaultdict对象收集您的ID,并enumerate()生成它们:

from collections import defaultdict

output = defaultdict(list)

for index, sentence in enumerate(inputlist):
    for word in sentence.lower().split():
         output[word.strip('!?. ')].append(index) 

请注意,我将句子小写并删除任何剩余的标点符号。

结果:

defaultdict(<class 'list'>, {'are': [0, 1], 'they': [0], 'be': [2], 'who': [0], 'yes': [2], 'there': [1, 2], 'you': [1, 2]})

这使用基于0的索引(就像Python中的所有内容一样)。如果 从1开始计数,请告诉enumerate()从那里开始计数:

for index, sentence in enumerate(inputlist, 1):

答案 1 :(得分:1)

我会像这样解决这个问题:

def toDict(l):
    ids, output,i = {}, {},1
    for sentence in l:
        ids[sentence] = i
        i += 1
    for sentence in l:
        words = sentence.split(" ")
        for word in words:
            if word in output:
                output[word].append(ids[sentence])
            else:
                output[word] = []
                output[word].append(ids[sentence])
    return output

返回:

 {'be': [3], 'there': [3], 'who': [1], 'Yes!': [3], 'there?': [2], 'are': [1, 2], 'they': [1], 'you': [2, 3]}

答案 2 :(得分:0)

这个有趣的解决方案怎么样:

import string
a = ['who are they','are you there?','Yes! you be there']
x ={}
for word in ' '.join(a).translate(None,string.punctuation).lower().split():
    try:x[word]+=1
    except:x[word]=1
print x
  • join()字符串列表形成一个字符串,因为你不关心单词的组织方式
  • translate()删除标点符号
  • 将所有字符降低()为小写,这样就不会以不同的方式处理“是”和“是”
  • 将字符串split()分为单词
  • 尝试,除了代码高尔夫你的方式围绕更长的if语句