?\|'_python 输出英语单词词性">
当前位置:   article > 正文

python英文文本词性分析_python 输出英语单词词性

python 输出英语单词词性

导入需要的库

  1. from nltk.tag import pos_tag
  2. from nltk.tokenize import word_tokenize

代码:

  1. def getText():
  2. txt = open('comment.text','r',encoding='utf-8').read()
  3. txt = txt.lower()
  4. for ch in r'`~!\'''@#$%^&*()_+-={}[];":,./<>?\|':
  5. txt = txt.replace(ch," ")
  6. return txt
  7. txt = getText()
  8. words = pos_tag(word_tokenize(txt))
  9. # print(words)
  10. counts = {}
  11. for word in words:
  12. counts[word[1]] = counts.get(word[1],0) + 1
  13. items = list(counts.items())
  14. items.sort(key = lambda x:x[1],reverse=True)
  15. print("该文本含有的词种类以及数量如下:")
  16. for i in range(len(counts)):
  17. pos,count = items[i]
  18. print("{0:<10}{1:>5}".format(pos,count))

可以新增查询功能:

  1. a = input("是否需要查询某种词的具体内容?(Y/N)")
  2. while a in ['Y','y']:
  3. b = input("请输入你要查询的词性:(输入all查看含有的词性种类)")
  4. while b in ['all','All','ALL']:
  5. print(counts.keys())
  6. b = input("请输入你要查询的词性:(输入all查看含有的词性种类)")
  7. if b in counts.keys():
  8. for word in words:
  9. if word.flag == b:
  10. print(word,end=" ")
  11. print()
  12. b = input("是否还要继续查询?(Y/N)")
  13. if b in ['N','n']:
  14. break
  15. else:
  16. print("你的输入不正确!请重新输入!")
  17. a = input("是否需要查询某种词的具体内容?(Y/N)")
  18. if a in ['N','n'] or b in ['N','n']:
  19. print("感谢使用!程序退出")
  20. else:
  21. print("你的输入有误!程序退出!")

结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/355517
推荐阅读
相关标签
  

闽ICP备14008679号