我目前正在尝试使用Python从文本文件中提取信息。我想从文件中提取一个子集,并将其存储在与文本文件中出现的任何地方无关的单独文件中。为了让您大致了解我的文件,下面是一个示例:
C","datatype":"double","value":25.71,"measurement":"Temperature","timestamp":1573039331258250},
{"unit":"%RH","datatype":"double","value":66.09,"measurement":"Humidity","timestamp":1573039331258250}]
在这里,我要提取"value"
及其旁边的相应数字。我尝试了各种技术,但未成功。我试图遍历文件,然后停在我有"value"
的位置,但这没用。
以下是代码示例:
with open("DOTemp.txt") as openfile:
for line in openfile:
for part in line.split():
if "value" in part:
print(part)
答案 0 :(得分:1)
首先使用,(逗号)作为分隔符进行拆分,然后使用:分隔符拆分相应的字符串。 如果需要,请在开头和结尾处修饰“”,然后与值进行比较
答案 1 :(得分:1)
返回“值”键标记的值的简单解决方案:
with open("DOTemp.txt") as openfile:
for line in openfile:
line = line.replace('"', '')
for part in line.split(','):
if "value" in part:
print(part.split(':')[1])
请注意,默认情况下,str.split()
在空白处分割。在最后一行中,如果我们将列表中的元素零打印出来,那么它将只是“值”。如果您希望将其用作int或float,则只需将其强制转换并返回。
答案 2 :(得分:1)
以下代码将为您工作:
file1 = open("untitled.txt","r")
data = file1.readlines()
#Convert to a single string
val = ""
for d in data:
val = val + d
#split string at comma
comma_splitted = val.split(',')
#find the required float
for element in comma_splitted:
if 'value' in element:
out = element.split('"value":')[1]
print(float(out))
答案 3 :(得分:1)
我假设您的输入文件是一个json字符串(词典列表)(查看文件示例)。如果是这样,也许您可以尝试一下。
import json
#Assuming each record is a dictionary
with open("DOTemp.txt") as openfile:
lines = openfile.readlines()
records = json.loads(lines)
out_lines = list(map(lambda d: d.get('value'), records))
with open('DOTemp_out.txt', 'w') as outfile:
outfile.write("\n".join(out_lines))