Python 中删除字符串中所有 URL 的正则表达式

chi*_*-yu 6 python regex

我想删除句子中的所有网址。

\n

这是我的代码:

\n
import ijson\nf = open("/content/drive/My Drive/PTT \xe7\x88\xac\xe8\x9f\xb2/content/MakeUp/PTT_MakeUp_content_0_1000.json")\nobjects = ijson.items(f, \'item\')\n\nfor obj in list(objects):\n    article = obj[\'content\']\n    ret = re.findall("http[s*]:[a-zA-Z0-9_.+-/#~]+ ", article) # Question here\n    for r in ret:\n        article = article.replace(r, "")\n    print(article)\n
Run Code Online (Sandbox Code Playgroud)\n

但句子中仍然留下了一个带有“http”的URL。

\n
article_example = "\xe7\x9c\xbc\xe5\xbd\xb1\xe7\x9b\xa4\xe9\x95\xb7\xe9\x80\x99\xe6\xa8\xa3 http://i.imgur.com/uxvRo3h.jpg \xe8\xaa\xaa\xe7\x9c\x9f\xe7\x9a\x84 \xe5\xbe\x88\xe4\xb8\x8d\xe5\xa5\xbd\xe6\x8b\x8d"\n
Run Code Online (Sandbox Code Playgroud)\n

我该如何修复它?

\n

Tim*_*sen 5

一个简单的修复方法是将模式替换https?://\\S+为空字符串:

\n
article_example = "\xe7\x9c\xbc\xe5\xbd\xb1\xe7\x9b\xa4\xe9\x95\xb7\xe9\x80\x99\xe6\xa8\xa3 http://i.imgur.com/uxvRo3h.jpg \xe8\xaa\xaa\xe7\x9c\x9f\xe7\x9a\x84 \xe5\xbe\x88\xe4\xb8\x8d\xe5\xa5\xbd\xe6\x8b\x8d"\noutput = re.sub(r'https?://\\S+', '', article_example)\nprint(output)\n
Run Code Online (Sandbox Code Playgroud)\n

这打印:

\n
\xe7\x9c\xbc\xe5\xbd\xb1\xe7\x9b\xa4\xe9\x95\xb7\xe9\x80\x99\xe6\xa8\xa3  \xe8\xaa\xaa\xe7\x9c\x9f\xe7\x9a\x84 \xe5\xbe\x88\xe4\xb8\x8d\xe5\xa5\xbd\xe6\x8b\x8d\n
Run Code Online (Sandbox Code Playgroud)\n

我的模式假设 URL 后面http://https://属于 URL 的一部分的任何非空白字符。

\n