【问题标题】:to check if a file belongs to a class in python检查文件是否属于python中的类
【发布时间】:2013-06-29 12:54:04
【问题描述】:

我有 5 节课,

即:

earn

acq

money

fx

crude

我有一个大约 20000 个文件的列表, 我有一个文件“topics.txt”,格式为:

earn~6~7~4

grain~9~1~2~12

money~4~29

等等.. 其中数字对应文件名,单词对应类。

我需要打印仅属于我之前提到的类的所有文件,即; “赚取”、“acq”、“money”、“fx”和“原油”

ex 输出: (earn-6.txt,7.txt,4.txt)

(acq-5.txt)

等等..

我可以打印“topics.txt”中所有可用的类,但我只想打印 5 个特定的类。

import collections
import sys
sys.stdout=open('dicti1.txt','w')
with open('topics.txt') as f:
    d = collections.defaultdict(list)
    for line in f:
        value, *keys = line.strip().split('~')
        for key in filter(None, keys):
            d[key].append(value+".txt")


for i in d.items():
    print(i)    

【问题讨论】:

  • “仅在我之前提到的类下”是什么意思?不打印还有其他标签的文件?
  • 标签下的文件:earn,acq,money,fx,crude

标签: python dictionary python-3.x machine-learning


【解决方案1】:

除非我误解了问题,否则您正在努力工作。另外我建议不要覆盖sys.stdout

试试这样的:

interesting_types = ['earn', 'acq', 'money', 'fx', 'crude']
with open("in.txt") as in_file, open('out.txt', 'w') as out_file:
    for l in in_file:
        if l:
            type, *filenames = l.strip().split("~")
            if type in interesting_types:
                out_file.write("({}-{})\n".format(type, ",".join(["{}.txt".format(x) for x in filenames])))

【讨论】:

  • 它在哪里引发值错误,在 split("~") 行中?
  • 那么我猜你的输入文件包含多个 ~ 每行...你能仔细检查你输入的信息吗?
  • 是的,确实如此!对不起,它的形式是:赚~6~7~4粒~9~1~2~12钱~4~29等等..
猜你喜欢
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多