简体   繁体   English

python 正则表达式用空格替换所有 windows 换行符

[英]python regex to replace all windows newlines with spaces

I did this:我这样做了:

from urllib import urlopen
import nltk
url = http://myurl.com
html = urlopen(url).read()
cleanhtml = nltk.clean_html(html)

I now have a long string in python which is full of text interrupted periodically by windows newlines /r/n , and I simply want to remove all of the occurrences of /r/n from the string using a regular expression.我现在在 python 中有一个长字符串,其中充满了由 windows 换行符/r/n定期中断的文本,我只想使用正则表达式从字符串中删除所有出现的 /r/n 。 First I want to replace it with a space.首先,我想用空格替换它。 As such, I did this:因此,我这样做了:

import re
textspaced = re.sub("'\r\n'", r"' '", cleanhtml)

...it didn't work. ......它没有工作。 So what am I doing wrong?那么我做错了什么?

There's no need to use regular expressions, just不需要使用正则表达式,只需

htmlspaced = html.replace('\r\n', ' ')

Your program didn't work since you added additional quotes, you only need one set.由于您添加了额外的引号,您的程序无法正常工作,您只需要一组。

Just a small syntax error:只是一个小的语法错误:

htmlspaced = re.sub(r"\r\n", " ", html)

should work.应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM