【问题标题】:Extracting specific data from a text file从文本文件中提取特定数据
【发布时间】:2018-10-03 14:16:41
【问题描述】:

大家好,我有一个文件,其中包含一些随机信息,但我只想要对我很重要的部分。

name: Zack
age: 17
As Mixed: Zack:17
Subjects opted : 3
Subject #1: Arts
name: Mike
age: 15
As Mixed: Mike:15
Subjects opted : 3
Subject #1: Arts

以上是我的文本文件示例,我希望将 Zack:17Mike:15 部分写入文本文件,而忽略其他所有内容。

我观看了一些 YouTube 视频并在 python 中遇到了 split 语句,但它不起作用。

我的代码示例

with open("/home/ninja/Desktop/raw.txt","r") as raw:
    for rec in raw:
        print rec.split('As Mixed: ')[0]

这不起作用。 任何帮助都会真正帮助我完成这个项目。 谢谢。

【问题讨论】:

  • 为什么不用你想要的信息创建一个数据框然后写出来呢?
  • 试试open(os.path.join(root, textfile), "r").readlines()[specified_line:]
  • “它不起作用”是什么意思?你有例外吗?如果有,是哪一个?您能否包含您获得的完整回溯(从Traceback (most recent call ...ExceptionType: <message>?结果不是您所期望的?那么您期望哪个结果,而您得到了哪个结果?程序有没有崩溃(例如程序以Segmentation fault 终止)?另外:您使用的语法是python2 语法,为什么要包含python-3.x 标签?唯一应该使用两个版本特定标签的情况是移植问题。

标签: python python-3.x python-2.7 split


【解决方案1】:

可以在:处拆分数据,只抓取As Mixed参数

content = [i.strip('\n').split(': ') for i in open('filename.txt')]
results = [b for a, b in content if a.startswith('As Mixed')]

输出:

['Zack:17', 'Mike:15']

将结果写入文件:

with open('filename.txt', 'w') as f:
  for i in results:
    f.write(f'{i}\n') 

【讨论】:

  • 我试过这个但得到这个错误 ValueError: too many values to unpack
【解决方案2】:

试试这个

import re
found = []
match = re.compile('(Mike|Zack):(\w*)')
with open('/hope/ninja/Destop/raw.twt', "r") as raw:
    for rec in raw:
        found.extend(match.find_all(rec))

print(found)
#output: [('Mike', '15'), ('Zack', '17')]

这使用正则表达式来查找所需的值,基本上(Mike|Zack):(\w*) 查找 Mike 或 Zack,然后查找 : 字符,然后找到尽可能多的单词。 要了解有关正则表达式的更多信息,您可以阅读此网站:https://docs.python.org/3.4/library/re.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2014-02-02
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多