【问题标题】:How do I only use one column of imported text file? [closed]如何只使用一列导入的文本文件? [关闭]
【发布时间】:2016-05-25 15:52:04
【问题描述】:

在我的代码中,我导入了 3 个不同的名称和数字列表,并且我想获得出现频率最低的名称。现在,我得到了所有名称的列表以及它们出现的次数。但该代码还计算了我不需要的所有其他列。

  1. 如何只分析文本文件的1列数据?

2.只用出现一次而不是多次出现的词出来回答?

import re

filelist = ['D.txt','A.txt','S.txt']
wordbank = {}
for file in filelist:
    article_one = re.findall('\w+', open(file,).read().lower())

    for word in article_one:
        word = word.lower().strip(string.punctuation)
        if word not in wordbank:
            wordbank[word] = 1
        else:
            wordbank[word] += 1

sortedwords = sorted(wordbank.items(), key=operator.itemgetter(1))

for word in sortedwords:
    print (word[1], word[0])

【问题讨论】:

    标签: python python-3.x text-files multiple-columns


    【解决方案1】:

    文本文件中的列是由什么分隔的?例如,假设它们是制表符分隔的列。无需使用正则表达式,您需要做的就是读取文本文件的每一行并用'\t' 分割该行。然后只使用第一列,取包含分割线的列表的索引零。

    您使用 wordbank 所做的应该足以找到仅出现一次的单词。您所要做的就是检查每个单词的计数以确保它不大于 1。例如:

    filelist = ['D.txt','A.txt','S.txt']
    wordbank = {}
    for file in filelist:
        f = open(file, 'r')
        lines = f.readlines()
        for l in lines:
            line = l.split('\t')
            word = line[0]
    
            if word not in wordbank:
                wordbank[word] = 1
            else:
                wordbank[word] += 1
        f.close()
    
    # Gather unique words
    unique_words = []
    for word in wordbank.keys():
        if wordbank[word] == 1:
            unique_words.append(word)
    

    【讨论】:

    • 我没有收到来自 unique_words 代码的任何响应
    • 我在上面提供了代码,展示了如何收集唯一词。当 for 循环完成时,您将拥有一个仅包含 unique_words 的列表。
    猜你喜欢
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多