【问题标题】:How to count strings in specified field within each line of one or more csv files如何计算一个或多个csv文件的每一行中指定字段中的字符串
【发布时间】:2021-03-02 12:54:50
【问题描述】:

编写一个 Python 程序(版本 3)来计算一个或多个 csv 文件的每一行中指定字段中的字符串。

csv 文件包含的位置:

Field1, Field2, Field3, Field4
A, B, C, D
A, E, F, G
Z, E, C, D
Z, W, C, Q

脚本被执行,例如:

$ ./script.py 1,2,3,4 file.csv

结果是:

A       10
C       7
D       2
E       2
Z       2
B       1
Q       1
F       1
G       1
W       1

错误 脚本被执行,例如:

$ ./script.py 1,2,3,4 file.csv file.csv file.csv

错误发生的地方:

for rowitem in reader:
    for pos in field:
        pos = rowitem[pos] ##<---LINE generating error--->##

        if pos not in fieldcnt:
            fieldcnt[pos] = 1

        else:
            fieldcnt[pos] += 1

TypeError:列表索引必须是整数或切片,而不是 str

谢谢!

【问题讨论】:

    标签: python-3.x linux parsing typeerror counting


    【解决方案1】:

    从输出来看,我会说 csv 文件中的字段不会影响字符串的计数。如果字符串唯一性不区分大小写,请记住使用yourstring.lower() 来返回字符串,以便不同的大小写匹配实际上算作一个。另外请记住,如果您的文本很大,您可能会发现的唯一字符串的数量也可能非常大,因此必须进行某种排序才能理解它! (否则它可能是一长串随机计数,其中很大一部分只是 1s)

    现在,使用 collections 模块获取唯一字符串的计数是一种简单的方法。

    file = open('yourfile.txt', encoding="utf8")
    a= file.read()
    
    #if you have some words you'd like to exclude
    stopwords = set(line.strip() for line in open('stopwords.txt')) 
    stopwords = stopwords.union(set(['<media','omitted>','it\'s','two','said']))
    # make an empty key-value dict to contain matched words and their counts
    wordcount = {}
    for word in a.lower().split(): #use the delimiter you want (a comma I think?)
        # replace punctuation so they arent counted as part of a word
        word = word.replace(".","")
        word = word.replace(",","")
        word = word.replace("\"","")
        word = word.replace("!","")
        if word not in stopwords:
            if word not in wordcount:
                wordcount[word] = 1
            else:
                wordcount[word] += 1
    

    应该这样做。 wordcount 字典应该包含这个词和它的频率。之后,只需使用collections 对其进行排序并打印出来。

    word_counter = collections.Counter(wordcount)
    for word, count in word_counter.most_common(20):
        print(word, ": ", count)
    

    我希望这能解决您的问题。让我知道您是否遇到问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-27
      • 2021-07-10
      • 1970-01-01
      • 2022-01-14
      • 2016-02-11
      • 1970-01-01
      • 2011-05-03
      • 1970-01-01
      相关资源
      最近更新 更多