Python 接收字符串为参数,用空格替换字符串中所有标点符号,根据空格将字符串切分为列表 返回值为元素为单词的列表
时间: 2023-07-16 19:13:53 浏览: 114
可以使用Python内置的string模块中的punctuation属性来获取所有标点符号,然后使用字符串的replace方法将标点符号替换为空格,最后使用split方法将字符串切分为列表。下面是实现这个功能的代码:
```python
import string
def process_text(text):
# 将标点符号替换为空格
translator = str.maketrans(string.punctuation, ' ' * len(string.punctuation))
text = text.translate(translator)
# 切分字符串为列表
word_list = text.split()
return word_list
```
这个函数接收一个字符串作为参数,将标点符号替换为空格并返回一个元素为单词的列表。可以调用这个函数来测试一下:
```python
text = "Hello, world! This is a test."
word_list = process_text(text)
print(word_list)
```
输出结果为:
```
['Hello', 'world', 'This', 'is', 'a', 'test']
```