开发者

python regex to replace all windows newlines with spaces

开发者 https://www.devze.com 2023-03-16 10:32 出处:网络
I did this: from urllib import urlopen import nltk url = http://myurl.com html = urlopen(url).read() cleanhtml = nltk.clean_html(ht开发者_JAVA百科ml)

I did this:

from urllib import urlopen
import nltk
url = http://myurl.com
html = urlopen(url).read()
cleanhtml = nltk.clean_html(ht开发者_JAVA百科ml)

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. 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', ' ')

If you need to also match UNIX and oldMac newlines, use regular expressions:

import re
htmlspaces = re.sub(r'\r\n|\r|\n', ' ', html)


Just a small syntax error:

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

should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消