我正在使用python中的代码进行工作,其中在文件的特定行中有两个单独的值。我想将两者作为单独的部分检索到matplotlib的列表中。这是我到目前为止的代码:
with open('data.txt') as data_file:
def process(line):
line = line.rstrip(data_file)
line = line.split('.')[1]
line = line.split(',')
return line
x = list()
y = list()
counter = 0
for line in data_file:
if (counter == 3) or (counter == 4):
result = process(line)
x.append(int(result[0]))
y.append(int(result[1]))
counter += 1
print(x)
print(y)
错误提示:
line = line.rstrip(data_file)
TypeError: rstrip arg must be None or str
一个示例文件是:
hi
hi
67, 78
2345, 45677
有人可以帮助我解决此错误,还是提供更好的方法来实现相同的结果。任何帮助表示赞赏!
非常感谢!
答案 0 :(得分:1)
这是我能想到的:
import re
regex = r'[\d]{1,3}, [\d]{1,3}'
result = []
with open('sample.txt') as f:
lines = f.readlines()
for line in lines:
match = re.findall(regex, line)
if match != []:
splitted = match[0].split(',')
#the values are mapped to a list containing floating point numbers
mapped = list(map(float, splitted))
#and then are appended to a list that will contain all of
#the lines that have the numbers on it
result.append(mapped)
print(result)
#this is how you could access each line in result
for list in result:
print(list)
输出
[[67.0, 78.0], [25.0, 18.0]] #result is a list containing all lines that have the pattern <number>, <number>
[67.0, 78.0] #the first line that matches the pattern
[25.0, 18.0] #the second one
这使用正则表达式查找最多3位数字(但您可以将其更改为所需的任何数字),匹配模式<number>, <number>
如果它与模式匹配,它将在,
处拆分两个数字,创建一个包含这两个值的列表,并将它们附加到结果列表中
希望有帮助。
任何问题都可以问。
修改
使用此文件作为示例文件向您示例:
hi
hi
67, 78
hi again
25, 18