小白教程

 找回密码
 立即注册
查看: 6385|回复: 3

[已解决]尝试将匹配词导入字典,同时返回错误"大写"

[复制链接]

1

主题

3

帖子

6

积分

新手上路

Rank: 1

积分
6
发表于 2021-5-21 04:08:40 | 显示全部楼层 |阅读模式
  1. from __future__ import print_function
  2. import string
  3. import re
  4. import unittest

  5. # You want to build a word cloud, an infographic where the size of a
  6. # word corresponds to how often it appears in the body of text.

  7. # To do this, you'll need data. Write code that takes a long string and
  8. # builds its word cloud data in a dictionary, where the keys are
  9. # words and the values are the number of times the words occurred.

  10. # Think about capitalized words. For example, look at these sentences:

  11. #  'After beating the eggs, Dana read the next step:'
  12. #  'Add milk and eggs, then add flour and sugar.'

  13. # What do we want to do with "After", "Dana", and "add"? In this
  14. # example, your final dictionary should include one "Add" or "add" with
  15. # a value of 22. Make reasonable (not necessarily perfect) decisions
  16. # about cases like "After" and "Dana".

  17. # Assume the input will only contain words and standard punctuation.


  18. # ignore all punctuation except sentence enders . ! and ?

  19. # lowercase any word that starts a sentence IFF it is also in the
  20. # corpus of words as a lowercase word.

  21. # How?

  22. # split corpus into sentences (strings ending with a . ? or !)
  23. # strip sentences into words
  24. # push all words into a case sensitive, word frequency counting, dict
  25. # scan the dict
  26. #   if a cap word is in the dict as cap and downcase then downcase
  27. # return dict

  28. # we do make two passes through the input stream, but if this were a
  29. # real problem, I'd use a lexing and parsing library to implement a
  30. # real world's problem's requirements.


  31. def word_cloud(input):
  32.     """map string of words into a dict of word frequencies"""

  33.     sentence_enders = r"\.|!|\?"
  34.     sentences = re.split(sentence_enders, input)

  35.     freq = {}
  36.     for sentence in sentences:
  37.         words = re.split(r"[^a-zA-Z0-9-]+", sentence)
  38.         for word in words:
  39.             count = freq.get(word, 0)
  40.             freq[word] = count + 1

  41.     def is_cap(word):
  42.         ch = word[0:1]
  43.         return ch in string.uppercase

  44.     for word, count in freq.items():
  45.         if is_cap(word) and word.lower() in freq:
  46.             count = freq[word]
  47.             freq[word.lower()] += count
  48.             del freq[word]

  49.     return freq


  50. class TestWordCloud(unittest.TestCase):

  51.     def test_examples(self):
  52.         """test the given example"""
  53.         test = 'After beating the eggs, Dana read the next step:' + \
  54.             'Add milk and eggs, then add flour and sugar-free diet coke.'
  55.         soln = {
  56.             'After': 1,
  57.             'Dana': 1,
  58.             'add': 2,
  59.             'and': 2,
  60.             'beating': 1,
  61.             'coke': 1,
  62.             'diet': 1,
  63.             'eggs': 2,
  64.             'flour': 1,
  65.             'milk': 1,
  66.             'next': 1,
  67.             'read': 1,
  68.             'step': 1,
  69.             'sugar-free': 1,
  70.             'the': 2,
  71.             'then': 1,
  72.         }

  73.         cloud = word_cloud(test)
  74.         self.assertDictEqual(soln, cloud)

  75.     def test_more_examples(self):
  76.         "test some additional examples"

  77.         tests = [
  78.             ["We came, we saw, we conquered...then we ate Bill's "
  79.              "(Mille-Feuille) cake."
  80.              "The bill came to five dollars.",
  81.              {
  82.                  'Mille-Feuille': 1,
  83.                  'The': 1,
  84.                  'ate': 1,
  85.                  'bill': 2,
  86.                  'cake': 1,
  87.                  'came': 2,
  88.                  'conquered': 1,
  89.                  'dollars': 1,
  90.                  'five': 1,
  91.                  's': 1,
  92.                  'saw': 1,
  93.                  'then': 1,
  94.                  'to': 1,
  95.                  'we': 4
  96.              }
  97.              ]
  98.         ]

  99.         for test, soln in tests:
  100.             cloud = word_cloud(test)
  101.             self.assertDictEqual(soln, cloud)


  102. if __name__ == "__main__":
  103.     unittest.main()
  104.     suite = unittest.TestLoader().loadTestsFromTestCase(TestWordCloud)
  105.     unittest.TextTestRunner(verbosity=2).run(suite)
复制代码


最佳答案
2021-5-30 04:27:32
我很好地理解你的逻辑,你首先是在字典中添加所有单词。然后,您正在做大量的工作来检查字典,并将以大写字母开出的单词移动到小写字母中的同一个单词,并删除以大写字母开出的单词。
我的建议是:首先降低所有键的低位。然后字典不需要后处理。
  1. freq = {}
  2. for sentence in sentences:
  3.     words = re.split(r"[^a-zA-Z0-9-]+", sentence)
  4.     for word in words:
  5.         count = freq.get(word.lower(), 0)
  6.         freq[word.lower()] = count + 1
复制代码
回复

使用道具 举报

2

主题

4

帖子

10

积分

新手上路

Rank: 1

积分
10
发表于 2021-5-24 14:28:00 | 显示全部楼层
返回每个字符在给定的翻译表中映射的字符串的副本。表必须是通过__getitem__(),通常是映射或序列实现索引的对象。当由 Unicode 定向(整数)索引时,表对象可以进行以下任何工作:返回 Unicode 定向或字符串,将字符映射到一个或多个其他字符:返回无,从返回字符串中删除字符:或提出一个查找异常,以映射自己的字符。
您可以使用 str.maketrans() 以不同格式创建不同格式的字符到字符映射的翻译映射。
回复

使用道具 举报

1

主题

5

帖子

11

积分

新手上路

Rank: 1

积分
11
发表于 2021-5-28 13:45:27 | 显示全部楼层
你在字典"freq"上翻来翻去。但是,然后你从字典中删除一个项目。因此,Python 不知道如何继续迭代。在迭转时,不允许更改字典
回复

使用道具 举报

0

主题

3

帖子

6

积分

新手上路

Rank: 1

积分
6
发表于 2021-5-30 04:27:32 | 显示全部楼层 &
我很好地理解你的逻辑,你首先是在字典中添加所有单词。然后,您正在做大量的工作来检查字典,并将以大写字母开出的单词移动到小写字母中的同一个单词,并删除以大写字母开出的单词。
我的建议是:首先降低所有键的低位。然后字典不需要后处理。
  1. freq = {}
  2. for sentence in sentences:
  3.     words = re.split(r"[^a-zA-Z0-9-]+", sentence)
  4.     for word in words:
  5.         count = freq.get(word.lower(), 0)
  6.         freq[word.lower()] = count + 1
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 12:30 , Processed in 0.025469 second(s), 27 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

快速回复 返回顶部 返回列表