gpt4 book ai didi

python - 在 Python 中替换字符串中的特殊字符

转载 作者:太空狗 更新时间:2023-10-29 17:21:05 27 4
gpt4 key购买 nike

我正在使用 urllib 从网站获取一串 html,需要将 html 文档中的每个单词放入一个列表中。

这是我目前的代码。我不断收到错误消息。我也复制了下面的错误。

import urllib.request

url = input("Please enter a URL: ")

z=urllib.request.urlopen(url)
z=str(z.read())
removeSpecialChars = str.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")

words = removeSpecialChars.split()

print ("Words list: ", words[0:20])

这里是错误。

Please enter a URL: http://simleyfootball.com
Traceback (most recent call last):
File "C:\Users\jeremy.KLUG\My Documents\LiClipse Workspace\Python Project 2\Module2.py", line 7, in <module>
removeSpecialChars = str.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")
TypeError: replace() takes at least 2 arguments (1 given)

最佳答案

一种方法是使用 re.sub ,这是我的首选方式。

import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string

输出:

hey there

另一种方法是使用 re.escape :

import string
import re

my_str = "hey th~!ere"

chars = re.escape(string.punctuation)
print re.sub(r'['+chars+']', '',my_str)

输出:

hey there

只是一个小技巧,关于 python 中的参数样式 PEP-8参数应该是 remove_special_chars 而不是 removeSpecialChars

此外,如果你想保留空格,只需将 [^a-zA-Z0-9\n\.] 更改为 [^a-zA -Z0-9\n\.]

关于python - 在 Python 中替换字符串中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23996118/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com