【问题标题】:Split String in Text File to Multiple Rows in Python在 Python 中将文本文件中的字符串拆分为多行
【发布时间】:2020-06-15 14:27:53
【问题描述】:

我在文本文件中有一个字符串,读取为一行,但我需要根据分隔符将字符串拆分为多行。如果可能的话,我想根据分隔此处列出的不同行元素的句点 (.) 来分隔字符串中的元素:

"第 1 行:元素 '{URL1}Decimal':'x' 不是原子类型 'xs:decimal' 的有效值。第​​ 2 行:元素 '{URL2}pos':'y' 不是原子类型“xs:double”的有效值。第​​ 3 行:元素“{URL3}pos”:“y z”不是列表类型“{list1}doubleList”的有效值”

这是我当前的脚本,它能够读取 .txt 文件并将其转换为 csv,但不会将每个条目分隔到自己的行中。

import glob
import csv
import os

path = "C:\\Users\\mdl518\\Desktop\\txt_strip\\"

with open(os.path.join(path,"test.txt"), 'r') as infile, open(os.path.join(path,"test.csv"), 'w') as outfile:
       stripped = (line.strip() for line in infile)
       lines = (line.split(",") for line in stripped if line)
       writer = csv.writer(outfile)
       writer.writerows(lines)

如果可能,我希望能够只写入具有多行的 .txt,但 .csv 也可以 - 非常感谢任何帮助!

【问题讨论】:

    标签: python pandas csv text automation


    【解决方案1】:

    使其工作的一种方法:

    import glob
    import csv
    import os
    
    path = "C:\\Users\\mdl518\\Desktop\\txt_strip\\"
    
    with open(os.path.join(path,"test.txt"), 'r') as infile, open(os.path.join(path,"test.csv"), 'w') as outfile:
           stripped = (line.strip() for line in infile)
           lines = ([sent] for para in (line.split(".") for line in stripped if line) for sent in para)
           writer = csv.writer(outfile)
           writer.writerows(lines)
    

    解释如下:

    输出是一行,因为最后一行的代码读取了一个二维数组,并且该二维数组中只有一个实例,即整个段落。为了可视化,“行”存储为[[s1,s2,s3]],其中 writer.writerows() 将行输入为[[s1],[s2],[s3]]

    可以有两个改进。

    (1) 取句号 '.'作为分隔符。 line.split(".")

    (2) 迭代列表推导中的拆分列表。 lines = ([sent] for para in (line.split(".") for line in stripped if line) for sent in para)

    str.split() 按分隔符拆分字符串并将实例存储在列表中。在您的情况下,它尝试将列表存储在列表理解中,使其成为二维数组。它将您的段落保存到 [[s1,s2,s3]]

    【讨论】:

    • Zwjjoy - 这绝对有帮助,但仍然需要进行一项调整!澄清一下,URL(例如 URL1)包含正式的网址(例如standards.iso.org/iso),因此“iso”存储在 csv 的一行中,其余 URL“org/.../../”写在下一行,两者之间有一个空格。再次感谢您一直以来的帮助,非常感谢!
    • @mdl518 乐于助人!有很多方法可以让它工作。我建议先预处理您的输入文本文件并将句子存储在列表中。一种方法是通过扩展现有代码来使其工作,即在正则表达式 re.split() 中使用 split 函数。建议的代码可以是:import relines = (['Line' + sent] for para in (re.split(r'Line', line) for line in stripped if line) for sent in para if sent)
    猜你喜欢
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2012-04-21
    • 2021-06-29
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多