我正试着用长串数单词的频率。我使用string.split()方法将字符串拆分为单词列表,并在拆分长字符串之前应用string.lower()删除大小写。我想删除一些特殊字符,如“!”、“:”、“”。因为这些角色会把单词计数搞砸。下面是我编写的函数,但它似乎不能正常工作。
def clean_word(word):
replace_list = [':','.',',','!','?']
s = list(word)
for i in s:
for j in replace_list:
if i == j:
i=""
print(s) # to see s before it being joined
word =''.join(s)
return word
print(clean_word('Hello!'))结果是:
“h”,“e”,“l”,“l”,“o”,“!”
你好!
我想知道为什么"!“还没有用"“代替?我确实在行中输入了一个测试代码,它显示了比较的效果。
if i == j:
print('Checked')发布于 2018-06-20 07:44:36
使用enumerate
def clean_word(word):
replace_list = [':','.',',','!','?']
s = list(word)
for i, x in enumerate(s):
if x in replace_list:
s[i] = ""
word = ''.join(s)
return word
print(clean_word('Hello!'))
# Hello如果你对清单感兴趣-理解:
word = 'Hello!'
replace_list = [':','.',',','!','?']
print(''.join([x for x in word if x not in replace_list]))
# Hello发布于 2018-06-20 07:47:07
它可以更容易地解决:
def clean_word(word):
replace_list = [':','.',',','!','?']
for i in replace_list:
word = word.replace(i,"")
return word
print(clean_word('Hello!'))代码错误:在编写i=""的代码中,它更改变量i的值,而不是原始字符串。
发布于 2018-06-20 07:48:15
def clean_word(word):
replace_list = [':','.',',','!','?']
new_word = ''
for x in word:
if x not in replace_list:
new_word += x
return new_word
print(clean_word('Hello!'))输出
Hellohttps://stackoverflow.com/questions/50942814
复制相似问题