Python在计算单词方面不如java方便

2024-10-01 04:55:04 发布

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

我只是在学习Python,找到了一些甚至不如Java8方便的地方,比如word count

一开始我认为它很容易实现,就像

>>> {x : x**2 for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

但实际上我发现它有点麻烦

>>> sent3
['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']
>>> for w in sent3:
...     if w in word_count:
...         word_count[w] += 1
...     else:
...         word_count[w] = 1
...

但在Java8中实现起来非常方便

    List<String> strings = asList("In", "the", "beginning", "God", "created", "the", "heaven", "and", "the", "earth");
    Map<String, Long> word2CountMap = strings.stream().collect(groupingBy(s -> s, counting()));

或者

    word2CountMap = new HashMap<>();
    for (String word : strings) {
        word2CountMap.compute(word, (k, v) -> v == null ? 1 : v + 1);
    }

我想知道是否存在一些高级的Python用法dict可以实现它更容易,我不知道?你知道吗


Tags: theinforstringcountwordcreatedstrings
3条回答

你应该看看collections.Counter

In [1]: from collections import Counter

In [2]: c = Counter(['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.'])

In [3]: c
Out[3]:
Counter({'.': 1,
         'God': 1,
         'In': 1,
         'and': 1,
         'beginning': 1,
         'created': 1,
         'earth': 1,
         'heaven': 1,
         'the': 3})

下面是一种使用collections模块中的^{}计算单词的更快方法。你知道吗

>>> from collections import Counter
>>> sent3 = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']
>>> Counter(sent3) 
Counter({'the': 3, 'In': 1, 'beginning': 1, 'God': 1, 'created': 1, 'heaven': 1, 'and': 1, 'earth': 1, '.': 1})

如果您想要一个dict对象而不是Counter类型的对象:

>>> dict(Counter(sent3))
{'In': 1, 'the': 3, 'beginning': 1, 'God': 1, 'created': 1, 'heaven': 1, 'and': 1, 'earth': 1, '.': 1}

虽然您可以使用collections.Counter()—我建议您使用它—但是您可以使用字典理解轻松完成您的要求—这是一个与Python习惯用法紧密相关的概念:

>>> sent3 = ['In',
...  'the',
...  'beginning',
...  'God',
...  'created',
...  'the',
...  'heaven',
...  'and',
...  'the',
...  'earth',
...  '.']
>>> {word : sent3.count(word) for word in sent3}
{'.': 1,
 'God': 1,
 'In': 1,
 'and': 1,
 'beginning': 1,
 'created': 1,
 'earth': 1,
 'heaven': 1,
 'the': 3}
>>> 

你看,问题很少是一种编程语言的功能不如另一种。这似乎是因为当你学习一门新语言时,你还没有必要的经验去了解适合某些任务的特定语言特性,这里就是这样。你知道吗

然而,这并不是说所有的语言都是一样的。每种语言都有差异,每种语言都有不同的哲学和不同的习语。当学习一门新语言时,最好问“我可以用这种方式用Java做X。Python的惯用方法是什么?”而不是“我可以用这种方式在Java中使用X。在Python中,它没有那么方便。“

相关问题 更多 >