我是Python的新手。我想解析一个文本文件,其中第一行包含标题并且是键,而下一行(第二行)具有其对应的值。
我面临的问题是文本文件中的内容不对称,这意味着第一行和第二行之间存在不均匀的空间,因此,我也无法使用定界符。
此外,没有必要在下一行中标头始终具有相应的值。有时可能是空的。
在那之后,我想使其成为具有这些键值对的JSON格式。
任何帮助将不胜感激。
import re
with open("E:\\wipro\\samridh\\test.txt") as read_file:
line = read_file.readline()
while line:
#print(line,end='')
new_string = re.sub(' +',' ', line)
line= read_file.readline()
print(new_string)
我的文字输入的PFA图片
答案 0 :(得分:1)
您可以使用finditer
包中的re
找到标头的索引和匹配项。然后,使用它来处理其余的内容:
import re
import json
thefile = open("file.txt")
line = thefile.readline()
iter = re.finditer("\w+\s+", line)
columns = [(m.group(0), m.start(0), m.end(0)) for m in iter]
records = []
while line:
line = thefile.readline()
record = {}
for col in columns:
record[col[0]] = line[col[1]:col[2]]
records.append(record)
print(json.dumps(records))
我将其留给OP去除空格并过滤出空条目。更不用说错误处理了;-)。
答案 1 :(得分:0)
不太清楚您要做什么,但是如果我正确理解并在以下假设下理解:-文件中只有2行。 -您拥有相同数量的键和值。 -值或键“内部”不允许有空格,这意味着除元素之间分隔的空格外,不允许其他任何空格。
with open(fname) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
此后,content[0]
是您的关键行,content[1]
是您的值。
现在您需要做的就是这个
key_value_dict = {}
for key,value in zip(content[0].split(), content[1].split()):
key_value_dict[key] = value
,并且您的key_value_dict包含键和值的字典(类似于JSON)。
答案 2 :(得分:0)
我假设每个标题都是一个单词,并且中间没有空格。然后,要找出每一列的起始位置,可以执行此操作,例如:
with open("E:\\wipro\\samridh\\test.txt") as read_file:
line = next(read_file)
headers = line.split()
l_bounds = [line.find(word) for word in headers]
分割数据线时,您还将需要正确的边界。如果您知道,例如,您的数据行都不超过1000个字符,则可以执行以下操作:
r_bounds = l_bounds[1:] + [1000]
遍历数据线时,将左右限制和header_words放在一起,如下所示:
out_str = json.dumps({name: line[l:r].strip()
for name, l, r in zip(headers, l_bounds, r_bounds)})
顺便说一句,不需要正则表达式。
答案 3 :(得分:-1)
以下假设:
此方法的好处是值之间可以有空格(如您的示例中所示)。如果您将标题字符串和值字符串都用空格分开,则它们将具有不同数量的元素,并且您将无法将它们组合在一起。另外,您将无法找到空值(如他的示例)。
这是我要采取的方法...
如果您确定文件头只有一个单词(没有空格),则查找每个单词的第一个字符的所有索引并将它们存储在数组中。每次您找出两个索引时,请提取它们之间的标题。所以在(header1-firstchar,header2-firstchar-1)之间...
然后获取第二行,并从索引中依次提取子字符串:(header1-firstchar,header2-firstchar-1)...
完成后,将提取的标题/键和值组合到字典中。
dictVerson = zip(headers, values)
然后致电:
import json
jsonVersion = json.dumps(dictVersion)