Python 如何从txt(就职演说)中删除标点符号?
下面的代码设法删除了就职演说中txt中的所有停止词,但我唯一的问题是,我还需要从列表中删除标点符号。任何关于我如何能做到这一点的帮助Python 如何从txt(就职演说)中删除标点符号?,python,Python,下面的代码设法删除了就职演说中txt中的所有停止词,但我唯一的问题是,我还需要从列表中删除标点符号。任何关于我如何能做到这一点的帮助 def content_text(inaugural): stopwords = set(nltk.corpus.stopwords.words('english')) w_stp = Counter() wo_stp = Counter() for word in inaugural: word = word.
def content_text(inaugural):
stopwords = set(nltk.corpus.stopwords.words('english'))
w_stp = Counter()
wo_stp = Counter()
for word in inaugural:
word = word.lower()
if word in stopwords:
w_stp.update([word])
else:
wo_stp.update([word])
return [k for k,_ in w_stp.most_common(10)],[y for y,_ in wo_stp.most_common(10)]
print(content_text(nltk.corpus.inaugural.words('1861-Lincoln.txt', )))
print(content_text(nltk.corpus.inaugural.words('1941-Roosevelt.txt', )))
print(content_text(nltk.corpus.inaugural.words('1945-Roosevelt.txt', )))
print(content_text(nltk.corpus.inaugural.words('1981-Reagan.txt', )))
print(content_text(nltk.corpus.inaugural.words('1985-Reagan.txt', )))
这个怎么样:
for word in inaugural:
word = word.lower().replace(',', '').replace(';','').replace('.',''))
if len(word.strip()) > 0:
if word in stopwords:
w_stp.update([word])
else:
wo_stp.update([word])
根据需要添加更多标点符号
说明:
在处理每个单词时,检查是否有标点符号。如果有,请将其移除。接下来,检查整个单词是否是标点符号。如果是,则长度为0,无需进一步处理。否则,处理剩余的单词
原始建议
def content_text(inaugural):
inaugural = inaugural.replace(',', '').replace(';','').replace('.',''))
(... the rest of the method...)
这是错误的,因为就职典礼不是字符串@Sam注意到了这个错误。实现这一点的一个好方法是使用正则表达式:
import re
re.sub('[^A-Za-z0-9]+', ' ', nltk.corpus.inaugural.words(**replace with speeches**))
这将删除所有不是单词或数字的字符 您可以使用Python和函数,如下所示:
import string
def remove_punctuation(s):
return s.translate(str.maketrans(string.punctuation, " " * len(string.punctuation))).replace(" ", " ")
print(remove_punctuation("Test@this!!out"))
这将显示以下内容:
Test this out
你有完整的标点符号列表吗?还是仅仅!“#$%&\'()*+,-./:;?@[\\]^
{124;}”~`will doTwo Thinks:#1-为什么要保留数字?#2-你不应该用空格替换标点符号吗?似乎如果你什么都不替换它们,你只会得到一长串字母字符和数字,无法识别一个单词的开头和结尾,我想这是这个人想要的之后可以这样做。数字可以在演讲中使用,比如“30年前”“或诸如此类。关于第二点,你是对的-我在我的帖子中编辑了正则表达式以反映这一点。@ArtOfWarfare我认为你不应该用空格代替标点符号。标点符号后面通常跟一个空格,除非在行尾。不管怎样,引入额外的空间可能不是最好的主意。是的,但是如果你计算单词数,你想把30作为一个单词来计算吗?IDK,这取决于提问者想要什么。这可能在上下文中很重要,取决于具体情况-至少,这是我的思考过程。:-)但你是对的,这取决于提问者。重新编写正则表达式以排除数字不会太困难。我得到一个属性错误:对象没有属性“replace”,这意味着什么?@Sam这意味着inituary
不是一个字符串。我已经用我认为正确的答案更新了答案。我现在就把解释打出来。