【问题标题】:Python Extract data from filePython 从文件中提取数据
【发布时间】:2012-09-24 08:05:53
【问题描述】:

我有一个文本文件,只是说

text1 text2 text text
text text text text

我希望首先计算文件中字符串的数量(全部由空格分隔),然后输出前两个文本。 (文字 1 文字 2)

有什么想法吗?

提前感谢您的帮助

编辑:这是我目前所拥有的:

>>> f=open('test.txt')
>>> for line in f:
    print line
text1 text2 text text text text hello
>>> words=line.split()
>>> words
['\xef\xbb\xbftext1', 'text2', 'text', 'text', 'text', 'text', 'hello']
>>> len(words)
7
if len(words) > 2:
    print "there are more than 2 words"

我遇到的第一个问题是,我的文本文件是:text1 text2 text text text

但是当我拉出单词的输出时,我得到: ['\xef\xbb\xbftext1', 'text2', 'text', 'text', 'text', 'text', 'hello']

'\xef\xbb\xbf 从何而来?

【问题讨论】:

  • 到目前为止你尝试过什么?你遇到了什么问题?这是非常基本的 python,但如果您的代码有特定问题,我们可以提供帮助。
  • 在原帖中更新

标签: python python-2.7


【解决方案1】:

要逐行读取文件,只需在for 循环中循环打开的文件对象:

for line in open(filename):
    # do something with line

要按空格将一行拆分成一个单独的单词列表,请使用str.split()

words = line.split()

要计算 python 列表中的项目数,请使用len(yourlist)

count = len(words)

要从 python 列表中选择前两项,请使用切片:

firsttwo = words[:2]

我将把构建完整程序的工作留给你,但你只需要上面的内容,再加上一个if 语句,看看你是否已经有了你的两个词。

您在文件开头看到的三个额外字节是UTF-8 BOM(字节顺序标记);它将您的文件标记为 UTF-8 编码,但它是多余的,仅在 Windows 上真正使用。

您可以使用以下方法将其删除:

import codecs
if line.startswith(codecs.BOM_UTF8):
    line = line[3:]

您可能希望使用该编码将字符串解码为 un​​icode:

line = line.decode('utf-8')

你也可以使用codecs.open()打开文件:

file = codecs.open(filename, encoding='utf-8')

请注意,codecs.open() 不会为您剥离 BOM;最简单的方法是使用.lstrip():

import codecs
BOM = codecs.BOM_UTF8.decode('utf8')
with codecs.open(filename, encoding='utf-8') as f:
    for line in f:
        line = line.lstrip(BOM)

【讨论】:

  • 非常感谢!我最初使用的是读取文件的 numpy/ascii 模块。我是 python(第 2 天)的新手,所以我会努力学习并随时更新
猜你喜欢
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
  • 2021-03-27
  • 1970-01-01
相关资源
最近更新 更多