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

标签 python string list replace urllib

我正在使用 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/

相关文章:

python - TypeError 参数太多

c - 从 C 中的字符串中删除所有 '\'

list - 如何在 Julia 中存储循环结果

c# - 我不认为我正在修改这个集合

python - 在 seaborn 中绘制 datetime.time

python - 将新列插入 numpy 数组

python - 如何使用 python (requests/urllib3) 登录 facebook?

java - 以 maner 方式设置 JTextField 宽度以包装给定文本

java - 检查字符串是否包含字母

java - 将 List<Subclass> 传递给需要 List<SuperClass> 的方法