用python将两个单词和类别列表与自己的语料库链接起来
好吧,我反复考虑了一遍,但我只是python的初学者,没有找到任何解决方案。 这就是我需要做的: 我有一个LIWC的文本文件,里面有各种各样的荷兰语单词和数字:用python将两个单词和类别列表与自己的语料库链接起来,python,list,dictionary,Python,List,Dictionary,好吧,我反复考虑了一遍,但我只是python的初学者,没有找到任何解决方案。 这就是我需要做的: 我有一个LIWC的文本文件,里面有各种各样的荷兰语单词和数字: aaien 12 13 32 aan 10 aanbad 12 13 14 57 58 38 ... 01:Pronoun 02:I 03:We 04:Self 05:You 06:Other ... 然后我从LIWC得到一个文本文件,后面有一个数字和一个类别: aaien 12 13 32 aan 10 aanbad 12 13
aaien 12 13 32
aan 10
aanbad 12 13 14 57 58 38
...
01:Pronoun
02:I
03:We
04:Self
05:You
06:Other
...
然后我从LIWC得到一个文本文件,后面有一个数字和一个类别:
aaien 12 13 32
aan 10
aanbad 12 13 14 57 58 38
...
01:Pronoun
02:I
03:We
04:Self
05:You
06:Other
...
现在我要把我自己的语料库和荷兰语单词联系起来,并把这些分类。因此,首先我必须将我的荷兰语单词与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)我不确定您要创建的最终格式是什么。例如,您可以制作一个字典,其中
dict['deone']
包含文档中包含'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']}
或者,您可以将文档
中的数字替换为文档1
中的条目
#for example from this format
dic = {'word1': [1,2,3], 'word2':[3,2]}
ref = {1: 'pronoun', 2: 'I' , 3: 'you'}
for word in dic:
for indx in range(len(dic[word])):
dic[word][indx] = ref[dic[word][indx]]
print dic
>>>{'word1': ['pronoun', 'I', 'you'], 'word2': ['you', 'I']}
否则,您是否考虑过数据库 这里有一种方法可以将数据转换成这种格式
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
,右侧将是ref[1]
,可以是“代词”
。这将给我们留下{'apple':['deone',2,3]
,剩下的数字将在下一次迭代中被替换。{'word1':['deone','I','you'],'word2':['you','I']}=>我想这就是我需要的,但是当我运行代码时,python给出了一个错误:keyrerror:“39”是39在我称之为ref
字典中定义的吗?如果ref:
中的dic[word][indx]在第二个for
之后,你可以通过来解决这个问题。但是这会保留原来的数字。现在它只给我dic{'word1':[1,2,3],'word2':[3,2]}再次…没有任何变化