使用for循环去除标点符号

4

我被指定编写一个for循环来移除字符串列表中的某些标点符号,并将答案存储在新列表中。我知道如何在一个字符串中完成此操作,但不知道如何在循环中处理。

例如:phrases = ['hi there!', 'thanks!'] 等等。

import string
new_phrases = []
for i in phrases:
    if i not in string.punctuation

接下来我有点困惑。我是要添加内容吗?我尝试了yieldreturn,但意识到那只适用于函数。


请写出您期望的输出 - sachin dubey
你的 for 循环没有起作用,因为 if 语句没有缩进(所以 if 在 for 的作用域之外)。 - DDS
你可以更新当前列表或将新值附加到另一个列表中。更新操作更好,因为它占用恒定的空间,而附加操作需要O(n)的空间。 - Pankaj Singh
8个回答

2

您可以更新当前列表或将新值附加到另一个列表中。更新会更好,因为它只需要恒定的空间,而附加需要O(n)的空间。

phrases = ['hi there!', 'thanks!']
i = 0
for el in phrases:
    new_el = el.replace("!", "")
    phrases[i] = new_el
    i += 1
print (phrases)

将输出:['嗨,你好', '谢谢']

问题要求将结果返回到一个新列表中。 - FrancoisB

1

试一试这个:

import re
new_phrases = []

for word in phrases:
    new_phrases.append(re.sub(r'[^\w\s]','', word))

使用正则表达式库将所有标点符号替换为空字符串。本质上是将其删除。

1
如果短语包含任何标点符号,则将其替换为""并附加到新短语中。
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']

1
你可以使用re模块和列表推导式在一行代码中完成它:
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']

0

或者只允许空格和字母:

phrases=[''.join(x for x in i if x.isalpha() or x==' ') for i in phrases]

现在:

print(phrases)

是:

['hi there', 'thanks']

0

根据您的思路,我会这样做:

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

0
我建议您在输入列表的每个字符串上使用强大的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']

-2

你应该使用列表推导式

new_list = [process(string) for string in phrases]

1
这个评论与问题无关。 - DDS
提问者明确表示他知道如何为一个字符串做到这一点。我打算给出方向而不是解决作业。但是,讨厌者总是要讨厌 ¯_(ツ)_/¯ - Simas Joneliunas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接