Python关键字读取程序,在删除标点符号时遇到问题

2024-06-09 14:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

Hi一直在玩一个简单的程序,它可以读入文本并识别首字母大写的关键字。我遇到的问题是,这个程序不会删除单词中的标点符号,我的意思是,佛罗多佛罗多。佛罗多,是不同的条目,而不是相同的条目。我试着使用导入字符串和标点符号,但没有成功

下面是我的代码,我使用的文本来自http://www.angelfire.com/rings/theroaddownloads/fotr.pdf(复制到名为novel.txt的txt文档中)。 再次感谢

by_word = {}
with open ('novel.txt') as f:
  for line in f:
    for word in line.strip().split():
      if word[0].isupper():
        if word in by_word:
          by_word[word] += 1
        else:
          by_word[word] = 1

by_count = []
for word in by_word:
  by_count.append((by_word[word], word))

by_count.sort()
by_count.reverse()

for count, word in by_count[:100]:
  print(count, word)

Tags: in文本程序txtforbyifcount
2条回答

希望以下内容能如预期的那样对您有效:

import string
exclude = set(string.punctuation)

by_word = {}
with open ('novel.txt') as f:
  for line in f:
    for word in line.strip().split():
      if word[0].isupper():
        word = ''.join(char for char in word if char not in exclude)
        if word in by_word:
          by_word[word] += 1
        else:
          by_word[word] = 1

by_count = []
for word in by_word:
  by_count.append((by_word[word], word))

by_count.sort()
by_count.reverse()

for count, word in by_count[:100]:
  print(count, word)

它将删除所有的

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 

word

你的代码很好,去掉标点,用正则表达式拆分

for word in line.strip().split():

可以改为

for word in re.split('[,.;]',line.strip()):

其中,[]中的第一个参数包含所有标点符号。它使用re模块https://docs.python.org/2/library/re.html#re.split

相关问题 更多 >