【问题标题】:how to read excel data and optimize code in python如何在python中读取excel数据并优化代码
【发布时间】:2017-02-17 16:21:16
【问题描述】:

我的代码是计算令牌。 它从文本文件中获取输入。我想从 excel 中获取输入,但如何? 另一个问题是代码不适用于相对较大的数据。如何优化?

# start
import codecs
from collections import Counter
def count_char(Input):

#Input file
fi= codecs.open('G:\python-proj/text.txt' , 'r',encoding='utf-8')
Input= fi.read()

#count words
spli=Input.split()
freq = Counter(spli)
sum=len(list(freq.elements()))
print('Total Tokenes:\n ')       
print(sum)
print('\n')
count_char(Input)

【问题讨论】:

  • 关于阅读 Excel 文件,您的问题需要更有针对性。从 python-excel.org 开始,选择看起来最合适的库,尝试编写一些代码,在 StackOverflow 中搜索答案,然后将您遇到的任何问题作为问题发布,以及显示您尝试过的代码。请参阅帮助中心的How do I ask a good question。我已经在下面回答了你问题的另一部分。

标签: python python-2.7 excel-2010


【解决方案1】:

Input= fi.read() 将整个文件读入内存。这就是为什么大文件会绊倒你的原因。解决方案是逐行阅读。

大文件仍然会让您感到困惑,因为您将单词保存在 Counter 对象中。如果重复项很少,那么该对象将变得非常大。如果重复是常见的内存将不是问题。

someCounter 有大量计数时,无论你做什么都不要调用list(someCounter.elements())。它将返回一个非常大的列表。 (如果someCounter = Counter({'redrum': 100000}) 那么list(someCounter.elements()) 会给你一个包含100000 个元素的列表!)

char_count = 0
word_counter = Counter()
with codecs.open('G:\python-proj/text.txt' , 'r',encoding='utf-8') as f:
    for line in f:
        char_count += len(line)
        word_counter.update(line.split())
unique_word_count = len(word_counter)
total_word_count = sum(word_counter.itervalues())

请注意,使用line.split() 可能会导致某些字词被视为唯一字词,而您不会认为它们是唯一字词。考虑:

>>> line = 'Red cars raced red cars.\n'
>>> Counter(line.split())
Counter({'cars': 1, 'cars.': 1, 'raced': 1, 'red': 1, 'Red': 1})

如果我们想将'red''Red' 一起计算而不考虑大小写,我们可以这样做:

>>> line = 'Red cars raced red cars.\n'
>>> Counter(s.lower().split()) # everything is made lowercase before counting
Counter({'red': 2, 'cars': 1, 'cars.': 1, 'raced': 1})

如果我们希望 'cars''cars.' 一起计算而不管标点符号,我们像这样去掉标点符号:

>>> import string
>>> punct = string.punctuation
>>> line = 'Red cars raced red cars.\n'
>>> Counter(word.strip(punct) for word in line.lower().split())
Counter({'cars': 2, 'red': 2, 'raced': 1})

关于阅读 Excel 文件,您的问题需要更有针对性。从python-excel.org 开始,选择最合适的库,尝试编写一些代码,在 StackOverflow 中搜索答案,然后将您遇到的任何问题作为问题发布,并附上显示您尝试过的代码。

【讨论】:

  • 我使用 Counter 是因为我不想计算重复的令牌。我是 python 中的大人物。
  • @kossaaar:更新答案。
【解决方案2】:

1) 您可以将 excel 文件保存为 .csv 文件,并使用 Python 的内置 CSV 阅读器对其进行解析。

2) 在大型数据集上速度很慢,因为您使用fi.read() 一次将整个文件读入内存。您可以计算每一行的标记:

for line in fi.read(): do something with (line.split())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    相关资源
    最近更新 更多