Python 3.x 删除带有特殊字符的完整字符串
在一个句子中,我想删除一个包含特殊字符的完整字符串 输入为Python 3.x 删除带有特殊字符的完整字符串,python-3.x,Python 3.x,在一个句子中,我想删除一个包含特殊字符的完整字符串 输入为[“我在球衣1&2”,“此代码为%bdn2*nn”] 预期输出为[“我在”,“此代码在”] 我得到 但预期的产出是有限的 Dsp1 = ["i am in", "this code is"] 使用str.isalpha Input = ["i am in jersey1&2","this code is %bdn2*nn"] for i in Input: print(" ".join(j for j in i.spl
[“我在球衣1&2”,“此代码为%bdn2*nn”]
预期输出为[“我在”,“此代码在”]
我得到
但预期的产出是有限的
Dsp1 = ["i am in", "this code is"]
使用
str.isalpha
Input = ["i am in jersey1&2","this code is %bdn2*nn"]
for i in Input:
print(" ".join(j for j in i.split() if j.isalpha()))
输出:
i am in
this code is
使用
str.isalpha
Input = ["i am in jersey1&2","this code is %bdn2*nn"]
for i in Input:
print(" ".join(j for j in i.split() if j.isalpha()))
输出:
i am in
this code is
您希望
re.sub
在单词级匹配和替换,其中单词是由字符串中的空格分隔的子字符串。正则表达式将在字符级别上匹配,除非您设法告诉它们其他情况(这有点复杂),或者在应用特殊的字符匹配正则表达式之前在空格上拆分字符串:
Dsp = ["i am in jersey1&2","this code is %bdn2*nn"]
Dsp1 = []
for sentence in Dsp:
cleaned_sentence = []
for word in sentence.split(' '):
if not re.search(r'\W'):
cleaned_sentence.append(word)
DSP1.append(' '.join(cleaned_sentence))
print(DSP1)
# ['i am in', 'this code is']
您希望
re.sub
在单词级匹配和替换,其中单词是由字符串中的空格分隔的子字符串。正则表达式将在字符级别上匹配,除非您设法告诉它们其他情况(这有点复杂),或者在应用特殊的字符匹配正则表达式之前在空格上拆分字符串:
Dsp = ["i am in jersey1&2","this code is %bdn2*nn"]
Dsp1 = []
for sentence in Dsp:
cleaned_sentence = []
for word in sentence.split(' '):
if not re.search(r'\W'):
cleaned_sentence.append(word)
DSP1.append(' '.join(cleaned_sentence))
print(DSP1)
# ['i am in', 'this code is']
这是因为当你在DSP中做<代码>:它会逐句遍历那个句子中的所有字符,这意味着它不会考虑每次迭代时在<代码> i < /代码>中的单个字符串。为什么不试着用分隔符“”拆分句子(空格),这样就有了一个单独字符串的列表。然后,你可以检查单个字符串并删除你不需要的字符串。这是因为当你在DSP中执行<代码>:时,它将逐句遍历该语句中的所有字符,这意味着在每次迭代中,它不会考虑在<代码> i < /代码>中的单个字符串。为什么不试着用分隔符“”拆分句子(空格),这样就有了一个单独字符串的列表。然后,您可以检查单个字符串并删除不需要的字符串。