YAS*_*YAS 0 python text file filter
我是Python新手(比如Zygote new),它只是为了补充另一个程序,但我需要的是我有一个文本文件,它是一组游戏项目,其格式如下:
[1]
Name=Blah
Faction=Blahdiddly
Cost=1000
[2]
Name=Meh
Faction=MehMeh
Cost=2000
[3]
Name=Lollypop
Faction=Blahdiddly
Cost=100
Run Code Online (Sandbox Code Playgroud)
我需要能够找出哪些组(括号中的数字)具有匹配的值。
因此,如果我搜索 Faction=Blahdiddly,第 1 组和第 3 组就会出现。
不幸的是我不知道该怎么做。
有人可以帮忙吗?
正如 Senthil 所指出的,ConfigParser 才是您真正想要读取的这样的文件。但是,它并没有提供一种按照您想要的方式过滤内容的简单方法。您可以这样做(获取部分列表,查看键是否在每个部分中,如果是,是否具有所需的值,如果是,则记录该部分),但这样的事情可能更简单。
datafile = open("datafile.txt")
section = None
found = []
match = set(["Faction=Blahdiddly"]) # can be multiple items
for line in datafile:
line = line.strip()
if line.startswith("[") and line.endswith("]"):
section = line.strip("[]")
elif line in match:
found.append(section)
print found
Run Code Online (Sandbox Code Playgroud)