gpt4 book ai didi

python - 用空格替换标点符号

转载 作者:太空狗 更新时间:2023-10-29 17:15:36 25 4
gpt4 key购买 nike

我的代码有问题,不知道如何继续。

tweet = "I am tired! I like fruit...and milk"
clean_words = tweet.translate(None, ",.;@#?!&$")
words = clean_words.split()

print tweet
print words

输出:

['I', 'am', 'tired', 'I', 'like', 'fruitand', 'milk']

我想要的是用空格替换标点符号,但不知道使用什么函数或循环。谁能帮帮我?

最佳答案

通过像这样更改“maketrans”很容易实现:

import string
tweet = "I am tired! I like fruit...and milk"
translator = string.maketrans(string.punctuation, ' '*len(string.punctuation)) #map punctuation to space
print(tweet.translate(translator))

它可以在我运行 python 3.5.2 和 2.x 的机器上运行。希望它也适用于您。

关于python - 用空格替换标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com