我正在尝试将以下数据从文本文件解析为熊猫:
genome Bacteroidetes_4
reference B650
source carotenoid
genome Desulfovibrio_3
reference B123
source Polyketide
reference B839
source flexirubin
我希望输出像这样:
genome,reference,source
Bacteroidetes_4,B650,carotenoid
Desulfovibrio_3,B123,Polyketide
Desulfovibrio_3,B839,flexirubin
我改编了一些代码(https://www.vipinajayakumar.com/parsing-text-with-python/由Vipin Ajayakumar编写)
import pandas as pd
import re
# write regular expressions
rx_dict = {
'genome': re.compile(r'genome (?P<genome>.*)\n'),
'source': re.compile(r'source (?P<source>.*)\n'),
'reference': re.compile(r'reference (?P<reference>.*)\n'),
}
# line parser
def parse_line(line):
for key, rx in rx_dict.items():
match = rx.search(line)
if match:
return key, match
# if there are no matches
return None, None
我相信文件解析器在while循环的某个地方有问题
def parse_file(filepath):
data = []
# open the file and read through it line by line
with open(filepath, 'r') as file_object:
line = file_object.readline()
while line:
# at each line check for a match with a regex
key, match = parse_line(line)
# extract from each line
if key == 'genome':
genome = match.group('genome')
if key == 'Source':
Source = match.group('Source')
if key == 'reference':
Type = match.group('reference')
while line.strip():
row = {
'genome': genome,
'reference': reference,
'Source': Source,
}
data.append(row)
data = pd.DataFrame(data)
return data
if __name__ == '__main__':
filepath = '/path/file.txt'
data = parse_file(filepath)
data.to_csv('output.csv', sep=',', index=False)
当我运行这段代码时,它会连续返回,没有结束。 任何关于如何纠正或排除故障的提示都将不胜感激
仅使用熊猫,我们可以使用
str.split
您的问题是在这里读取文件时
line的值永远不会改变,因此while循环会无休止地运行
更改为:
您是否尝试过在while循环中设置断点并使用调试器查看发生了什么
您只需使用:
使用Python>;=3.7. 对于旧版本:
然后在启用调试器的情况下运行脚本:
使用“c”继续到下一个断点。有关命令的详细信息,请参见the documentation
如果您使用的IDE具有集成调试器,那么也可以使用集成调试器,这样使用起来就不那么麻烦了
顺便说一句,这可能是因为您使用了
while line
,然后似乎从未读过新行,所以只要第一行不是空字符串,语句的计算结果就会为True,并无限期地停留在while循环中。您可以尝试使用for循环来迭代该文件例如
相关问题 更多 >
编程相关推荐