Bigram是一个看起来像的列表-
[('a', 'b'), ('b', 'b'), ('b', 'b'), ('b', 'c'), ('c', 'c'), ('c', 'c'), ('c', 'd'), ('d', 'd'), ('d', 'e')]
现在,我尝试将每个元素写入列表,如果该列表作为单独的行包含在具有此代码的文件中,
bigram = list(nltk.bigrams(s.split()))
outfile1.write("%s" % ''.join(ele) for ele in bigram)
但我收到此错误:
TypeError:write()参数必须是str,而不是生成器
我希望结果如文件中所示
('a', 'b')
('b', 'b')
('b', 'b')
('b', 'c')
('c', 'c')
......
您要将生成器解析传递给write
,该生成器需要字符串。
如果我理解正确,则希望每行写一个元组表示。
您可以通过以下方法实现:
outfile1.write("".join('{}\n'.format(ele) for ele in bigram))
要么
outfile1.writelines('{}\n'.format(ele) for ele in bigram)
第二个版本将生成器理解传递给writelines
,从而避免在写入之前在内存中创建大字符串(看起来更像是您的尝试)
它产生具有以下内容的文件:
('a', 'b')
('b', 'b')
('b', 'b')
('b', 'c')
('c', 'c')
('c', 'c')
('c', 'd')
('d', 'd')
('d', 'e')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句