我为这个令人困惑的头衔道歉。我是Python的新手,这就是我想要实现的目标:
我正在解析一个文件file.txt,它包含这样的数据(以及其他内容):
file.txt的:
...
a = (
1
2
3 )
...
我需要将这类数据分为两部分:
name =“a”
value = {“(”,“1”,“2”,“3)”} ^每行是列表的元素
我正在逐行解析文件,如下面的代码段所示,我无法改变它。我不确定如何通过向前看几行来存储数据,存储它们的值然后跳过它们以便它们不会被处理两次。 我希望当循环位于第一行“a =”
时填充2变量名称和值with open(file.txt) as fp:
for line in fp:
...
感谢您的帮助。
答案 0 :(得分:1)
我建议使用字典:
txt=open(r"file.txt","r").readlines()
dictionary=dict()
for i in range(len(txt)):
if "=" in txt[i]:
name,values=txt[i].split()[0],[txt[i].split()[-1]]
dictionary[name],i={"name":name},i+1
while True:
values.append(txt[i])
if ")" in txt[i]:
break
i=i+1
values=[value.replace("\n","") for value in values]
dictionary[name].update({"values":values})
i=i-1
i=i+1
>>dictionary["a"]
Out[40]: {'name': 'a', 'values': ['(', '1', '2', '3 )']}
>>dictionary["b"]
Out[45]: {'name': 'b', 'values': ['(', '3', '4', '6 )']}
答案 1 :(得分:0)
因此,您逐行解析文件。每当你在一行中找到等号“=”时,就意味着“=”之前的字符是你想要的名字值。然后下一行是列表的第一个元素,第二个元素之后的行等......当一行有char“)时,它表示它是列表的最后一个值。 See the Python string.find method for this。尝试理解这个概念,编码应该不难。
答案 2 :(得分:0)
[u'a']
['(', '1', '2', '3', ')']
这是你需要的吗?
然后你可以按照这些代码行:
import nltk
name = []
value = []
with open("file.txt") as fp:
for line in fp:
words = line.split()
if ('(') in words:
name.append(words[0].decode('utf-8'))
value.append('(')
else:
for entry in words:
value.append(entry)
print (name)
print (value)
fp.close()
答案 3 :(得分:0)
如果文件不是太大,请将整个文件读入内存,然后使用while循环进行更细粒度的控制:
# python3
with open("file.txt") as f:
lines = f.readlines()
index = 0
while True:
# do something here
否则,如果只有最后一个值包含')',请执行以下操作:
with open('file.txt') as f:
pairs = []
for line in f:
values = []
name, value = line.strip().split('=')
name = name.strip()
values.append(value.strip())
while True:
line = next(f)
values.append(line.strip())
if ')' in line:
break
pairs.append((name, values))