如何计算列表中元素的总数?

时间:2019-06-08 04:13:55

标签: python

因此,基本上,我必须设计一个程序,该程序使用POS_dic的各种选项来计算文本文件中的词汇总数

作为CC的POS_dic选项的示例,CC选项包含['but','nor','or','and'],一旦用户选择了任何文本文件,此程序就应计算每个CC元素的出现时间并显示结果的格式为{'but':x,'nor':x,'or':x,'and':x}

POS_dic = {'CC': ['but', 'nor', 'or', 'and'],
        'WRB': ['how', 'why', 'when'],
        'RP': ['up']
        }

file = str(input("Which File? "))
file_data = []
file_open = open(file,"r")

for file_word in file_open:

    file_data += file_word.split()

file_data = [x.lower() for x in file_data]
print(file_data)

while True:
    pos = str(input("Which Pos? "))

    if pos == "CC":
        cc_count = 0
        cc = POS_dic["CC"]

        for CC in cc:

            cc_list = cc[cc_count]
            cc_count += 1

            if cc_count > len(cc):
                break

            cc_total = []
            cc_final = 0

            for CC_check in cc_list:

                cc_result = cc_list.count(cc_list[cc_final])
                cc_final += 1

                if cc_final > len(cc_list):
                    break

                #cc_total.append(cc_list[cc_final]+cc_result)
            print(cc_list)

    else:
        break

3 个答案:

答案 0 :(得分:0)

如果我完全理解您的意思,我将执行以下操作:

from collections import Counter
POS_dic = {'CC': ['but', 'nor', 'or', 'and'],
        'WRB': ['how', 'why', 'when'],
        'RP': ['up']
        }

file = str(input("Which File? "))
file_data = []
file_open = open(file,"r")

for file_word in file_open:

    file_data += file_word.split()

file_data = [x.lower() for x in file_data]

count_word = {}
for k, v in POS_dic:
    count_word.update([(k,Counter(word for word in file_data if word in v)])

pos = str(input("Which Pos? "))

count_word.get(pos, None) # count word

功能计数器将对可迭代项目进行计数 https://docs.python.org/3.7/library/collections.html#collections.Counter

答案 1 :(得分:0)

我不确定这是否是您要实现的目标,但是无论如何。

import re

results = dict()
file_data = open('file.txt')

pos_dict = {
    'CC': {
        'but': re.compile(r'^but$|^but\s|\sbut\s|\sbut$|^But$|^But\s|\sBut\s|\sBut$|^BUT$|^BUT\s|\sBUT\s|\sBUT$'),
        'nor': re.compile(r'^nor$|^nor\s|\snor\s|\snor$|^Nor$|^Nor\s|\sNor\s|\sNor$|^NOR$|^NOR\s|\sNOR\s|\sNOR$'),
        'or': re.compile(r'^or$|^or\s|\sor\s|\sor$|^Or$|^Or\s|\sOr\s|\sOr$|^OR$|^OR\s|\sOR\s|\sOR$'),
        'and': re.compile(r'^and$|^and\s|\sand\s|\sand$|^And$|^And\s|\sAnd\s|\sAnd$|^AND$|^AND\s|\sAND\s|\sAND$')
    }
}

for row in file_data.readlines():
    for key, value in pos_dict.items():
        temp = results.get(key, dict())
        for text, pattern in value.items():
            existing_count = temp.get(text, 0)
            temp.update({text: existing_count+len(pattern.findall(row))})
        results.update({key: temp})

while True:
    pos = str(input("Which Pos? "))
    if pos not in pos_dict.keys():
        break
    print(results.get(pos, dict()))

您可以根据需要向pos_dict添加更多键值。 pos_dict包含正则表达式以匹配每个词汇(小写,标题大小写和大写)

还要确保我们完全匹配词汇表。每种情况有4种模式:
示例

^ BUT $ -以BUT开头,以BUT结尾,
用于仅包含一个单词但不包含行的行

^ BUT \ s -以BUT开头,以空格结尾,
适用于以BUT开头并带有其他单词的行

\ s BUT \ s -以带有BUT的空格开始,以空格结束,
用于在其他词之间具有BUT的行

\ s BUT $ -以空格开头,以BUT结尾,
用于以BUT结尾的行

让我知道是否有帮助,或者您有任何疑问。

这里是对python正则表达式的引用。

https://www.w3schools.com/python/python_regex.asp

这也是我第一次写答案,因此,如果可以使答案更清楚,请更正我。

答案 2 :(得分:0)

首先,str.split()不会为您提供完整的单词列表(不含标点符号和其他非单词字符),只会在空白处分割(例如,对于The quick brown. Fox jumps over.The lazy dog !,您会得到['The', 'quick', 'brown.', 'Fox', 'jumps', 'over.The', 'lazy', 'dog', '!'])。您必须对列表进行后处理才能删除/在标点符号上进一步拆分,这时正则表达式将成为更好的选择,即:

import re

filename = input('Which file? ')
with open(filename) as f:
    words = re.findall(r'\w+', f.read())

或者,如果您只有足够的内存来容纳单词列表而不是完整的文件内容,则可以通过逐行迭代文件来采用慢一点的方法:

import re

filename = input('Which file? ')
words = []  # an empty placeholder to fill iteratively
with open(filename) as f:
    for line in f:
        words += re.findall(r'\w+', line)

无论您如何获取单词列表,由于要忽略对单词计数的大小写,您可能只想小写文件内容(例如words = re.findall(r'\w+', f.read().lower())words += re.findall(r'\w+', line.lower())),以便您开始算数就不必再次遍历列表,只需将其小写即可。

一旦有了单词列表,就可以通过迭代计数器并检查当前单词是否在您感兴趣的列表中来设计自己的计数器,例如:

POS_dic = {'CC': ['but', 'nor', 'or', 'and'],
           'WRB': ['how', 'why', 'when'],
           'RP': ['up']
           }
pos = POS_dic.get(input('Which Pos? '))
pos_count = dict.fromkeys(pos, 0)  # lets create a counting dict from the values
for word in word_list:
    if word in pos_count:
        pos_count[word] += 1
print(pos_count)

但是这效率低下并且笨拙,特别是如果您想获得多个计数(如您的代码所示)的话-每次您要计数某些特定单词时都必须遍历单词列表。最好只对所有单词计数一次,然后再对感兴趣的单词计数就可以了。您可以自己这样做:

words_count = {}
for word in words:
    words_count[word] = words_count.get(word, 0) + 1

POS_dic = {'CC': ['but', 'nor', 'or', 'and'],
           'WRB': ['how', 'why', 'when'],
           'RP': ['up']
           }
pos = POS_dic.get(input('Which Pos? '))
pos_count = {p: words_count.get(p, 0) for p in pos}
print(pos_count)

但是Python的内置电池概念为您提供了通过collections.Counter()为您完成无聊工作的便利,因此您无需处理计数就可以卸载它:

import collections

words_count = collections.Counter(words)

POS_dic = {'CC': ['but', 'nor', 'or', 'and'],
           'WRB': ['how', 'why', 'when'],
           'RP': ['up']
           }
pos = POS_dic.get(input('Which Pos? '))
pos_count = {p: words_count.get(p, 0) for p in pos}  # filter the words_count
print(pos_count)

然后要获得总数,您可以将pos_count的值求和,例如:sum(pos_count.values())。因此,将其全部包装起来:

import collections
import re

POS_dic = {'CC': ['but', 'nor', 'or', 'and'],
           'WRB': ['how', 'why', 'when'],
           'RP': ['up']
           }

filename = input('Which file? ')
with open(filename) as f:
    words = re.findall(r'\w+', f.read())
words_count = collections.Counter(words)

while True:
    pos = POS_dic.get(input('Which Pos? '))
    if pos is None:  # input not in the POS_dic
        break
    pos_count = {p: words_count.get(p, 0) for p in pos}
    print(pos_count)  # individual counts as a dict
    print('Total: {}'.format(sum(pos_count.values()))  # sum of all the counts