属性文件将信息存储为键和值。 密钥是USER_NAME,PASSWORD,IP_ADD 和价值是fenfnewl,fnaofna,ftp.internal.com
我编写了python脚本来使用正则表达式提取信息并打印输出。输出看起来像
USER_NAME = fenfnewl
PASSWORD = fnaofna
IP_ADD = ftp.internal.com
我有变量V_USER_NAME,V_PASSWORD,V_IP_ADD。我希望这些变量得到如下值
V_USER_NAME = fenfnewl
V_PASSWORD = fnaofna
V_IP_ADD = ftp.internal.com
我写的从属性文件获取输出的代码如下,它工作正常。我只想在输出中将键从USER_NAME更改为V_USER_NAME。
#!/usr/bin/env python
import re # import the regular expressions module
import sys
import mysql.connector
val = 'DEFAULT'
print val
REG_EXP={'DEFAULT':r"\bDEFAULT_(USER_NAME|PASSWORD|IP_ADD)\w*\b",
'NOT_DEFAULT':r"\bNOT_DEFAULT_(USER_NAME|PASSWORD|IP_ADD)\w*\b"}
filename = "/Users/DOCUMENTS/some.properties"
if val != 'DEFAULT':
pattern = re.compile(REG_EXP['NOT_DEFAULT'], re.IGNORECASE)
with open(filename, "rt") as in_file:
for line in in_file:
if pattern.search(line) != None:
print(line)
else:
pattern = re.compile(REG_EXP['DEFAULT'], re.IGNORECASE)
with open(filename, "rt") as in_file:
for line in in_file:
if pattern.search(line) != None:
print(line)
我是python的初学者。任何帮助深表感谢。提前致谢
答案 0 :(得分:1)
如果你知道先验你想从文件中提取哪些变量,你总是可以创建一系列if / then语句,将数据放入你想要的变量中。例如:
import re
REG_EXP = re.compile(r'\bDEFAULT_(USER_NAME|PASSWORD|IP_ADD)\w*\b\s*=\s*(.*)') # give me the value as well as the key
with open(filename, 'rt') as in_file:
for line in in_file:
match = REG_EXP.search(line)
if match:
key = match.group(1)
value = match.group(2)
if key == 'USER_NAME':
V_USER_NAME = value
elif key == 'PASSWORD':
V_PASSWORD = value
elif key == 'IP_ADD':
V_IP_ADD = value
当然,我在这里暗示使用key
和value
。在python中处理此问题的另一种方法是创建一个dict
,其中键是变量名,其中您想要创建由某些用户输入确定的动态变量名。如果您不知道变量名称是什么,或者您不想写出所有if / then语句,这很有用:
import re
result = {} # keys will be variable names
REG_EXP = re.compile(r'\bDEFAULT_(\w*)\b\s*=\s*(.*)') # don't know what the variable names are!
with open(filename, 'rt') as in_file:
for line in in_file:
match = REG_EXP.search(line)
if match:
key = 'V_' + match.group(1)
value = match.group(2)
result[key] = value
print(result) # gives something like {'V_USER_NAME': 'fenfnewl', 'V_PASSWORD': 'fnaofna', ...}
如果您最终阅读了大量此类文件并进行此类解析,我是否可以建议您查看标准化的输入文件格式,例如JSON或YAML? Python有一些优秀的软件包可以直接将这些类型的文件读入dict
类似的结构,从而节省了编写自己的自定义解析器的工作。
最后,我不建议这样做,因为有可能执行任意代码,如果你真的想生成动态创建变量的代码,你总是可以调用exec
:< / p>
import re
REG_EXP = re.compile(r'\bDEFAULT_(\w*)\b\s*=\s*(.*)') # don't know what the variable names are!
with open(filename, 'rt') as in_file:
for line in in_file:
match = REG_EXP.search(line)
if match:
key = 'V_' + match.group(1)
value = match.group(2)
exec(key + '=' value) # PLEASE RECONSIDER!
print(V_USER_NAME) # will hopefully print something like "fenfnewl", but might also give hackers root access to your machine. Seriously.
如果您正在考虑实施最后一个解决方案,我建议您重新考虑!您已收到警告。