【问题标题】:How to create multiline lists from raw file and process them in python?如何从原始文件创建多行列表并在 python 中处理它们?
【发布时间】:2022-01-20 15:55:22
【问题描述】:

我有以下代码将raw_file.txt 转换为processed_file.txt。

问题一:

除了item_location,我还需要item_id(作为str,而不是int)在处理过的文件中,也许作为列表,所以它看起来像WANTED_processed_file.txt

def process_file(raw_file, processed_file, target1):
    with open(raw_file, 'r') as raw_file:
        with open(processed_file, 'a') as processed_file:
            for line in raw_file:
                if target1 in line:
                    processed_file.write(line.split(target1)[1])

process_file('raw_file.txt', 'processed_file.txt', 'item_location: ')

通过添加另一个带有target2 的if 语句,内容将附加在target1 下方(如预期的那样),但我实际上不知道如何将其设为列表。

问题 2:

使用我当前的代码,我只能处理与该行对应的字符串,但由于WANTED_processed_file.txt 包含多个列表,我需要对其进行调整。

def my_function():
    print(i)

with open('processed_file.txt', "r") as processed_file:
    items = processed_file.read().splitlines()
    for i in items:
        my_function()

这是我尝试过的,但我没有得到想要的结果:

def my_function():
    print(f'Item {i[0]} is located at {i[1]}')

with open('WANTED_processed_file.txt', "r") as processed_file:
    items = processed_file.read()
    for i in items:
        my_function()

raw_file.txt:

ITEM:
item_id: 0001
item_location: first location
item_description: something

ITEM:
item_id: 0002
item_location: second location
item_description: something else

processed_file.txt:

first location
second location

WANTED_processed_file.txt:

['0001', 'first location']
['0002', 'second location']

感谢您,并为冗长的帖子道歉

【问题讨论】:

  • 请不要在循环的每次迭代中打开文件。在进行文件 I/O 时使用 with 块

标签: python list file multiline


【解决方案1】:

您想从文本文件中解析多行块。稳健的方法是逐行处理它,搜索块标记和数据标记的开始,填充数据结构,然后将数据存储到文件中。

如果您确定您的项目将始终处于相同的顺序,您可以使用多行正则表达式:

import re
...
with open('raw_file.txt') as fd:
   text = fd.read()
rx = re.compile(r'ITEM:.*?item_id: ([^\n]*).*?item_location: ([^\n]*)',
                re.MULTILINE | re.DOTALL)
with open('processed_file', 'w') as fd:
    for record in rx.finditer(t):
        print(list(record), file=fd)

但请注意,它会不如真正的解析器强大...

【讨论】:

  • 必须将readall 更改为read,但我仍然会得到NameError: name 're' is not defined,如果我将其更改为某个已定义的变量,我会得到AttributeError: '_io.TextIOWrapper' object has no attribute 'compile'。 python 3.9对应的函数是什么?
  • @rocky-evasive-dosage:您必须导入 re 模块(请参阅我的编辑)。
猜你喜欢
  • 2021-09-23
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多