python字符串拼接的奇怪问题

约翰羊 2017-02-02 11:25:13
我从网页里按行读取的网页内容,用find找到特定的行,用+把后边几行拼接成一个新的字符串,但是+出来的字符串只有最后一段,debug跟了一下,显示的结果是正确的,但一运行就是不对,我又在字符串拼接的后边加了一个print,发现这个print语句根本没执行,后来改用join,有一个网页正常了,但是其他网页都还是不正确,还请前辈指点指点,谢谢。

代码是下面这样的

python 3

       
found = False
for line in html.split('\n'):
if(found):
post_html = post_html+line #结果是只保留了最后一次的line值,前面的都没存上,后来在这行下边加了print,但print根本就不执行,但用debug跟踪,全是正常的,但就是一运行就不对了。

if(line.find('</table>')>-1):
break
if line.find('<td class="t_msgfont" id="postmessage')>-1:
post_html= line
found = True
...全文
170 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
约翰羊 2017-02-03
  • 打赏
  • 举报
回复
引用 1 楼 u012536120 的回复:
代码逻辑没问题,就是缩进看着怪怪的。 你在循环外边加上这个——post_html='' 你说的只有最后一段,是只有这个吗?——</table> 你的代码是用“\n"来分行的,你确定你html里面是用\n分行吗 -------------------------------------------------------------------------------------- 感觉你写这个代码是想找到匹配某个开头结尾的,最小内容块。 你可以这样写啊。
import re

html=''
post_html=[]
with open('zz.html','r+') as f:
	html=f.read()
pattern=re.compile('<td class="t_msgfont" id="postmessage.*?</table>',re.S)
items=re.findall(pattern,html)
for item in items:
	post_html.append(item)

print(post_html)
谢谢回复 缩进是因为我粘过来的时候,又改了些代码,格式上有点点怪 我在for上边,有post_html='' 网页是\n分行 多谢提醒,我再试试正则 谢谢
sanGuo_uu 2017-02-03
  • 打赏
  • 举报
回复
代码逻辑没问题,就是缩进看着怪怪的。 你在循环外边加上这个——post_html='' 你说的只有最后一段,是只有这个吗?——</table> 你的代码是用“\n"来分行的,你确定你html里面是用\n分行吗 -------------------------------------------------------------------------------------- 感觉你写这个代码是想找到匹配某个开头结尾的,最小内容块。 你可以这样写啊。
import re

html=''
post_html=[]
with open('zz.html','r+') as f:
	html=f.read()
pattern=re.compile('<td class="t_msgfont" id="postmessage.*?</table>',re.S)
items=re.findall(pattern,html)
for item in items:
	post_html.append(item)

print(post_html)
sanGuo_uu 2017-02-03
  • 打赏
  • 举报
回复
引用 3 楼 john_sheep 的回复:
正则好用,谢谢
恩,不客气
约翰羊 2017-02-03
  • 打赏
  • 举报
回复
引用 1 楼 u012536120 的回复:
代码逻辑没问题,就是缩进看着怪怪的。 你在循环外边加上这个——post_html='' 你说的只有最后一段,是只有这个吗?——</table> 你的代码是用“\n"来分行的,你确定你html里面是用\n分行吗 -------------------------------------------------------------------------------------- 感觉你写这个代码是想找到匹配某个开头结尾的,最小内容块。 你可以这样写啊。
import re

html=''
post_html=[]
with open('zz.html','r+') as f:
	html=f.read()
pattern=re.compile('<td class="t_msgfont" id="postmessage.*?</table>',re.S)
items=re.findall(pattern,html)
for item in items:
	post_html.append(item)

print(post_html)
正则好用,谢谢

37,717

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧