我正在尝试解析txt文件中两个不同标签的内容,而我正在获取第一个标签的所有实例" p"但不是第二个" l"。问题是"或"?
感谢您的帮助。这是我正在使用的代码
with open('standardA00456.txt','w') as output_file:
with open('standardA00456.txt','r') as open_file:
the_whole_file = open_file.read()
start_position = 0
while True:
start_position = the_whole_file.find('<p>' or '<l>', start_position)
end_position = the_whole_file.find('</p>' or '</l>', start_position)
data = the_whole_file[start_position:end_position+5]
output_file.write(data + "\n")
start_position = end_position
答案 0 :(得分:1)
'<p>' or '<l>'
将始终等于'<p>'
,因为它告诉Python仅在'<l>'
为'<p>'
,None
时使用False
,数字为零,或空。由于字符串'<p>'
永远不会是其中之一,因此始终会跳过'<l>'
:
>>> '<p>' or '<l>'
'<p>'
>>> None or '<l>'
'<l>'
相反,您可以轻松使用re.findall
:
import re
with open('standardA00456.txt','w') as out_f, open('standardA00456.txt','r') as open_f:
p_or_ls = re.findall(r'(?:<p>.*?</p>)|(?:<l>.*?</l>)',
open_f.read(),
flags=re.DOTALL) #to include newline characters
for p_or_l in p_or_ls:
out_f.write(p_or_l + "\n")
但是,使用正则表达式解析带有标记(例如HTML和XML)的文件是 not a good idea 。使用BeautifulSoup之类的模块更安全:
from bs4 import BeautifulSoup
with open('standardA00456.txt','w') as out_f, open('standardA00456.txt','r') as open_f:
soup = BeautifulSoup(open_f.read())
for p_or_l in soup.find_all(["p", "l"]):
out_f.write(p_or_l + "\n")
答案 1 :(得分:-1)
英语Grad,我认为你需要改进逻辑。我修改了你的代码并想出了这个:
with open('standardA00456.txt','w') as output_file:
with open('standardA00456.txt','r') as open_file:
the_whole_file = open_file.read()
start_position = 0
found_p = False
fould_l = False
while True:
start_pos_p = the_whole_file.find('<p>', start_position)
start_pos_l = the_whole_file.find('<l>', start_position)
if start_pos_p > -1 and start_pos_l > -1:
if start_pos_p < start_pos_l:
found_p = True
start_position = start_pos_p
found_l = False
else:
found_l = True
start_position = start_pos_l
found_p = False
elif start_pos_p > -1:
found_p = True
start_position = start_pos_p
found_l = False
elif start_pos_l > -1:
found_l = True
start_position = start_pos_l
found_p = False
else:
break
if found_p:
end_position = the_whole_file.find('</p>', start_position)
elif found_l:
end_position = the_whole_file.find('</l>', start_position)
else:
break
data = the_whole_file[start_position:end_position+5]
output_file.write(data + "\n")
start_position = end_position