我必须在文本文件中找到变量的值。
我的文件采用以下形式:
AccountingStoragePort=8544
AccountingStorageUser=root
Name=touktouk Cards=45 Files=2015 State=UNKNOWN
如何获取例如 Files 的值(2015 年)
在此文件中,有 1 个“变量”/行或多个以空格分隔的“变量”。每个值都是唯一的(我的文件中没有 2 个文件)
另一方面,“Files”可以在任何行 => 例如第 3 行或第 150 行找到。
我无法修改此文件以与 ConfigParser 兼容。
我的conf文件有以“#”开头的注释,我必须排除我的研究中的这些行。
对于排除注释行,我尝试这样做,但它不起作用:
match = re.search(r"(?!#\s*)\bFiles=(\d+)", s)
我发现了问题,如果我的文件中有返回行,则您的代码不应用注释限制,例如:
import re
s = '''
AccountingStoragePort=8544
AccountingStorageUser=root
#Name=touktouk Cards=45 Files=2015 State=UNKNOWN
Name=touktouk Cards=45 Files=2017 State=UNKNOWN
'''
match = re.search(r'^[^#].*\bFiles=(\d+)', s, flags=re.MULTILINE)
if match:
value = match.group(1)
print (value)
该计划返回 2015 年而不是 2017 年
最佳答案
您可以使用re.search
。如果值为数字且变量出现 1 次或更少,则使用:
import re
s = '''AccountingStoragePort=8544
AccountingStorageUser=root
Name=touktouk Cards=45 Files=2015 State=UNKNOWN'''
match = re.search(r'\bFiles=(\d+)', s)
if match:
value = match.group(1)
print value
关于python - 在文本文件中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41573164/