如何在python中用数组值写入文件?

2024-09-29 01:28:48 发布

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

>>> w
['Parts-of-speech', 'disambiguation', 'techniques', '(', 'taggers', ')',
 'are', 'often', 'used', 'to', 'eliminate', '(', 'or', 'substantially',
 'reduce', ')', 'the', 'parts-of-speech', 'ambiguitiy', 'prior', 'to',
 'parsing.', 'The', 'taggers', 'are', 'all', 'local', 'in', 'the', 'sense',
 'that', 'they', 'use', 'information', 'from', 'a', 'limited', 'context',
 'in', 'deciding', 'which', 'tag', '(', 's', ')', 'to', 'choose', 'for',
 'each', 'word.', 'As', 'is', 'well', 'known', ',', 'these', 'taggers',
 'are', 'quite', 'successful', '.']
>>> q=open("D:\unieng.txt","w")
>>> q.write(w)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument 1 must be string or read-only character buffer, not list

Tags: orofthetoinspeechareused
3条回答

您需要使用join将列表连接到字符串中。更改写入

q.write(w)

q.write(''.join(w))

使用^{}方法编写内容。

>>> f   = open("test.txt",'w')
>>> mylist = ['a','b','c']
>>> f.writelines(mylist)

文件.writelines(序列)

Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value

注意:writelines()不添加行分隔符。

w是一个列表,错误说明文件对象的write方法不接受list。

您可以将w转换为字符串并按如下方式编写:

' '.join(w) #Joins elements with spaces in between

然后你可以打电话给:

q.write(str)

相关问题 更多 >