用python将两个词类列表与自己的语料库连接起来

2024-04-26 01:12:46 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我反复考虑过,但我只是python的初学者,我没有找到任何解决方案。 这就是我需要做的: 我有一个来自LIWC的文本文件,里面有各种荷兰语单词和数字:

aaien 12 13 32
aan 10
aanbad 12 13 14 57 58 38
...

然后我从LIWC得到一个文本文件,后面有一个数字和一个类别:

^{pr2}$

现在我要把我自己的语料库和荷兰语单词联系起来。所以首先我要把我的荷兰语单词和LIWC单词表中荷兰语后面的数字联系起来,然后我要把这些数字和这些类别联系起来。。。 我想把LIWC的这两个列表编成字典会很有用。 到目前为止我得到的是:

with open('LIWC_words.txt', 'rU') as document:
    answer = {}
    for line in document:
        line = line.split()
        if not line:  #empty line
            continue
        answer[line[0]] = line[1:]

with open ('LIWC_categories.txt','rU') as document1:
    categoriesLIWC = {}
    for line in document1:
        line = line.strip()
        if not line:
            continue
        key, value = line.split(':')
        if key.isdigit():
            categoriesLIWC[int(key)] = value
        else:
            categoriesLIWC[key] = value

所以我现在有两本字典。。。但现在我被卡住了。有人知道我下一步该怎么做吗?(我使用Python2.6.5,因为我主要需要使用NLTK)


Tags: keytxtif字典valueruwithline
2条回答

这里有一种将数据转换成这种格式的方法。在

dic = {}
ref = {}
tempdic = open('dic.txt','r').read().split('\n')
tempref = open('ref.txt','r').read().split('\n')

for line in tempdic:
  if line:
    line = line.split()
    dic[line[0]] = line[1:]
for line in tempref:
  if line:
    line = line.split(':')
    ref[line[0]] = line[1]
#dic = {'word1':[1,2,3], word2:[2,3]...}
#ref = {1:'ref1',2:'ref2',...}
for word in dic:
  for indx in range(len(dic[word])):#for each number after word
    dic[word][indx] = ref[dic[word][indx]]

假设我们从{'apple':[1,2,3]}开始。dic['apple'][0]将解析为1,右边是{},可能是{}。这将留给我们{'apple' : ['pronoun', 2, 3],剩下的数字将在下一次迭代中被替换。在

我不知道你到底想创建什么样的结束格式。例如,您可以制作一个字典,其中dict['pronoun']包含document中包含'01'的所有行。在

#for example from this format
dic = {'word1': [1,2,3], 'word2':[3,2]}
ref = {1: 'pronoun', 2: 'I' , 3: 'you'}

out = {}

for word in dic:
  for entry in dic[word]:
    if entry in out:
      out[entry].append(word)
    else:
      out[entry] = []
      out[entry].append(word)

print out
>>>{1: ['word1'], 2: ['word1', 'word2'], 3: ['word1', 'word2']}

或者,您可以将document中的数字替换为document1中的条目。在

^{pr2}$

否则你有没有想过要建立一个数据库?在

相关问题 更多 >