[英]How would I search a .txt file for something between <> python
我想在文本文件中搜索像这样在方括号之间的信息。
<fg="blue"><bg="red">
我想得到fg="blue"
。
然后,我想将"blue"
存储在变量中,但有任何线索如何实现?
您的示例字符串看起来像XML。 我建议您在Google搜索“ Python解析XML”或“ Python解析HTML”。
如果是XML,则可能需要ElementTree。
https://docs.python.org/2/library/xml.etree.elementtree.html
如果是HTML,则可能需要BeautifulSoup。
http://www.crummy.com/software/BeautifulSoup/
Google会在上述两个方面为您找到教程和文档。
好吧,对于这种简单的情况,您可以使用正则表达式。
import re
with open('myfile', 'r') as f:
f = f.read()
# use matches_a or matches_b depending on what you actually want
matches_a = re.findall(r'<([^=]+=\"[^"]+\")>', f)
matches_b = re.findall(r'<[^=]+=\"([^"]+)\">', f)
演示:
>>> import re
>>> s = '<fg="blue"><bg="red">'
>>> re.findall(r'<([^=]+=\"[^"]+\")>',s)
['fg="blue"', 'bg="red"']
>>> re.findall(r'<[^=]+=\"([^"]+)\">',s)
['blue', 'red']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.