Python 编写for循环以删除标点符号
我的任务是编写一个for循环来删除字符串列表中的一些标点符号,并将答案存储在一个新列表中。我知道如何用一个字符串来实现这一点,但不是在循环中 例如:Python 编写for循环以删除标点符号,python,python-3.x,Python,Python 3.x,我的任务是编写一个for循环来删除字符串列表中的一些标点符号,并将答案存储在一个新列表中。我知道如何用一个字符串来实现这一点,但不是在循环中 例如:phrases=[“你好!”,“谢谢!”]等等 import string new_phrases = [] for i in phrases: if i not in string.punctuation 然后我在这一点上有点卡住了。我需要附加吗?我尝试了yield和return,但意识到这是用于函数的。您应该使用列表理解 new_lis
phrases=[“你好!”,“谢谢!”]
等等
import string
new_phrases = []
for i in phrases:
if i not in string.punctuation
然后我在这一点上有点卡住了。我需要附加吗?我尝试了
yield
和return
,但意识到这是用于函数的。您应该使用列表理解
new_list = [process(string) for string in phrases]
您可以更新当前列表,也可以将新值附加到另一个列表中。更新会更好,因为它需要常量空间,而append需要O(n)空间 将给出输出:[“你好”,“谢谢”]试一试:
import re
new_phrases = []
for word in phrases:
new_phrases.append(re.sub(r'[^\w\s]','', word))
这使用正则表达式库将所有标点转换为“空白”字符串。基本上,如果短语包含任何标点符号,则将其删除,然后将其替换为“”,并附加到新的\u短语中
import string
new_phrases = []
phrases = ['hi there!', 'thanks!']
for i in phrases:
for pun in string.punctuation:
if pun in i:
i = i.replace(pun,"")
new_phrases.append(i)
print(new_phrases)
输出
['hi there', 'thanks']
您可以使用
re
模块和list comprehension
在单行中执行此操作:
phrases = ['hi there!', 'thanks!']
import string
import re
new_phrases = [re.sub('[{}]'.format(string.punctuation), '', i) for i in phrases]
new_phrases
#['hi there', 'thanks']
按照你的形式,我会这样做:
for word in phrases: #for each word
for punct in string.punctuation: #for each punctuation
w=w.replace(punct,'') # replace the punctuation character with nothing (remove punctuation)
new_phrases.append(w) #add new "punctuationless text" to your output
我建议您对输入列表的每个字符串使用功能强大的
translate()
方法,这似乎非常合适。它给出了以下代码,通过列表理解对输入列表进行迭代,该代码简短易读:
import string
phrases = ['hi there!', 'thanks!']
translationRule = str.maketrans({k:"" for k in string.punctuation})
new_phrases = [phrase.translate(translationRule) for phrase in phrases]
print(new_phrases)
# ['hi there', 'thanks']
或仅允许空格和字母:
phrases=[''.join(x for x in i if x.isalpha() or x==' ') for i in phrases]
现在:
是:
编写您的预期输出您的
for
没有做任何事情,因为如果语句没有缩进(因此如果超出范围),您可以更新当前列表或将新值附加到另一个列表中。更新会更好,因为它需要常量空间,而append需要O(n)空间。此注释与问题无关询问者明确表示他知道如何为一个字符串执行此操作。我打算给人指点方向,而不是解决家庭作业。但仇恨者会憎恨的“_(ツ)_/''要求在新列表中返回结果的问题。
phrases=[''.join(x for x in i if x.isalpha() or x==' ') for i in phrases]
print(phrases)
['hi there', 'thanks']