【问题标题】:one liner syntax python一种线性语法python
【发布时间】:2019-03-31 15:13:28
【问题描述】:

我想计算文件中每个单词的个数,我正在尝试编写它 作为一行代码,但我得到一个无效的语法错误,我不明白为什么, 或如何改变它。

我的代码:

def print_words(filename):
  my_file = open(filename, 'r')
  word_dict = {}
  for line in my_file:
    line.lower()
    words_in_line = line.split(" ")
    word_dict[word] += 1 if word_dict.get(word) else word_dict[word] = 0 
      for word in words_in_line

错误信息:

word_dict[word] += 1 if word_dict.get(word) else word_dict[word] = 0 for word in words_in_line
                                                                 ^
SyntaxError: invalid syntax

我也尝试将它写得有点不同(代码将如下)但仍然得到相同的错误。但是当我删除“= 0”时,语法是好的(当我从原来的一行中删除它时,语法仍然无效)。

my_file = open(filename, 'r')
word_dict = {}
for line in my_file:
  line.lower()
  words_in_line = line.split(" ")
  for word in words_in_line:
    word_dict[word] += 1 if word_dict.get(word) else word_dict[word] = 0

【问题讨论】:

  • 你让我们猜测错误是什么,在哪里。编辑问题以包含完整的错误消息。
  • 赋值不能是表达式的一部分。
  • 另外,您在定义word 之前使用word 作为索引。
  • 这可能是使用Counter 的好时机,正如here 所解释的那样。

标签: python syntax-error


【解决方案1】:

您可以使用正则表达式来获取单词和 Counter 类(来自集合)来计算它们:

from collections import Counter
import re
with open("testfile.txt") as file: words = Counter(re.findall("\w+",file.read()))

如果文件很大,可能需要逐行处理:

with open("testfile.txt") as file: words = Counter( w for line in file for w in re.findall("\w+",line.upper()))

【讨论】:

  • 1.如果我有一个几十 GB 的大文件怎么办,有没有比一次读取整个文件更有效的方法?这是最有效的方法吗? 2. 不区分大小写如何计算?
【解决方案2】:

def print_words(filename): my_file = (open(filename, 'r').readlines()) word_dict = {} for line in my_file: line.lower() words_in_line = line.replace("\n","").split(" ") for word in words_in_line: if word in word_dict: word_dict[word] =word_dict[word]+ 1 else: word_dict[word] = 1

【讨论】:

    【解决方案3】:

    使用默认字典而不是常规字典。

    from collections import defaultdict
    
    def print_words(filename):
        with open(filename, 'r') as my_file:
            word_dict = defaultdict(int)
            for line in my_file:
                for word in line.lower().split(" "):
                    word_dict[word] += 1
    
        ...
    

    或者更进一步,使用Counter

    from collections import Counter
    from itertools import chain
    
    def print_words(filename):
        flatten = chain.from_iterable
        with open(filename, 'r') as my_file:
            word_dict = Counter(flatten(line.lower().split(" ") for line in my_file))
    
        ...
    

    【讨论】:

      猜你喜欢
      • 2012-03-16
      • 2019-07-30
      • 2012-11-28
      • 2017-12-09
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多