【问题标题】:How do I split file content to write into another file?如何拆分文件内容以写入另一个文件?
【发布时间】:2019-02-15 05:14:27
【问题描述】:

每次我尝试拆分一个文件的内容并将它们写入另一个文件时都会收到类型错误。

该错误表明应该使用字符串而不是列表,因此我尝试先对其进行转换,但仍然收到相同的错误。该文件是一个去除了 html 标签的 html 页面,因此它只是纯文本

这是收到的错误

...............line 30, in split
w.write(re.split('[^\.\!\?]*[\.\!\?]',str(str1)))
TypeError: write() argument must be str, not list

这是python函数

def split():
x=open("file_a.txt")
w= open("file_b.txt","w+")
str1= x.readlines()
w.write(re.split('[^\.\!\?]*[\.\!\?]',str(str1)))

【问题讨论】:

  • split 的输出是一个列表。然后您尝试write 列表,但“写列表”是什么意思?会不会是[1, 2, 3],就像 Python 会写它一样?或1<newline>2<newline>3<newline>,每行一项?也许只是把元素粘在一起,比如123?用1, 2 and 3 加英文吗?具体来说,当您说“拆分一个文件的内容并将它们写入另一个文件”时,您想要什么?

标签: python regex python-3.x nltk


【解决方案1】:

str1 = x.readlines()

这里的 str1 将是您读取的文件中的行列表。相反,您希望在从文件中读取的每一行上运行拆分操作。

同样通过运行以下行,您正在尝试将列表写入输出文件。因为 re.split 操作返回一个列表。

w.write(re.split('[^.!\?]*[.!\?]',str(str1)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-24
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多