【问题标题】:extract words from a text file and print netxt line从文本文件中提取单词并打印下一行
【发布时间】:2020-08-15 18:26:59
【问题描述】:

样本输入

在解析文本文件时 .txt = ["'blah.txt'", "'blah1.txt'", "'blah2.txt'" ]

另一个文本文件 out_path.txt 中的预期输出

blah.txt 
blah1.txt
blah2.txt

我尝试过的代码,这只是将“[]”附加到输入文件。虽然我也尝试过用 perl 替换双引号和单引号。

read_out_fh = open('out_path.txt',"r")

for line in read_out_fh:

    for word in line.split():

        curr_line = re.findall(r'"(\[^"]*)"', '\n')

        print(curr_line)

【问题讨论】:

  • 用实际结果和预期结果格式化您的问题

标签: python-3.x list python-requests


【解决方案1】:

发生这种情况是因为当您读取文件时,即使您保留列表的格式,它也会被视为字符串而不是列表。这就是为什么你在做 re.for line in read_in_fh: 时得到 [] 的原因,你正在获取字符串中的每个字母,这就是为什么你没有得到所需的输出。所以我先写了一些东西把字符串转换成一个列表。在这样做的同时,我还消除了您提到的""''。然后将其写入新文件example.txt

注意:根据您的文件更改文件名

read_out_fh = open('file.txt',"r")
for line in read_out_fh:
    line=line.strip("[]").replace('"','').replace("'",'').split(", ")
    with open("example.txt", "w") as output:
        for word in line:
            #print(word)
            output.write(word+'\n')

example.txt(输出文件)

blah.txt
blah1.txt
blah2.txt 

【讨论】:

    【解决方案2】:

    以下代码适用于您在问题中给出的示例:

    # Content of textfile.txt:
        asdasdasd=["'blah.txt'", "'blah1.txt'", "'blah2.txt'"]asdasdasd
    
    
    # Code:
    
    import re
    
    read_in_fh = open('textfile.txt',"r")
    write_out_fh = open('out_path.txt', "w")
    
    
    for line in read_in_fh:
    
    
        find_list = re.findall(r'\[(".*?"*)\]', line)
    
    
        for element in find_list[0].split(","):
    
            element_formatted = element.replace('"','').replace("'","").strip()
    
            write_out_fh.write(element_formatted + "\n")
    
    
    write_out_fh.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多