Python大师,我需要从列表中提取所有文本直到URL,下面是模式的示例。我也希望脚本能够循环文件夹中的所有文件。Python - 从多个文件中提取多个字符串中的文本
.....
.....
<List>Product Line</List>
<URL>http://teamspace.abb.com/sites/Product</URL>
...
...
<List>Contact Number</List>
<URL>https://teamspace.abb.com/sites/Contact</URL>
....
....
预计输出
<List>Product Line</List>
<URL>http://teamspace.abb.com/sites/Product</URL>
<List>Contact Number</List>
<URL>https://teamspace.abb.com/sites/Contact</URL>
我已经开发了一个脚本,能循环所有在文件夹中的文件,然后提取从列表中开头的所有关键字,但我无法包含URL。非常感谢您的帮助。
# defining location of parent folder
BASE_DIRECTORY = 'C:\D_Drive\Projects\Test'
output_file = open('C:\D_Drive\Projects\\Test\Output.txt', 'w')
output = {}
file_list = []
# scanning through sub folders
for (dirpath, dirnames, filenames) in os.walk(BASE_DIRECTORY):
for f in filenames:
if 'xml' in str(f):
e = os.path.join(str(dirpath), str(f))
file_list.append(e)
for f in file_list:
print f
txtfile = open(f, 'r')
output[f] = []
for line in txtfile:
if '<List>' in line:
output[f].append(line)
tabs = []
for tab in output:
tabs.append(tab)
tabs.sort()
for tab in tabs:
output_file.write(tab + '\n')
output_file.write('\n')
for row in output[tab]:
output_file.write(row + '')
output_file.write('\n')
output_file.write('----------------------------------------------------------\n')
raw_input()
输入和预期的输出看起来是一样的。尝试改善你的问题 – fferri
为什么要重新发明车轮?只需使用xml解析器,如[xml树](https://docs.python.org/2/library/xml.etree.elementtree.html) – dawg
请更新缩进。 –