繁体   English   中英

如何从文本文件中读取并根据特定类别对行进行排序并将其打印在 python shell 上

[英]How to read from text files and sorted the lines based on a particular category and print it on python shell

如何读取文本文件并在我的 python shell 上打印行,但行必须与部件 ID 一起排序? 如何根据部件 ID 对这些行进行排序? (例如:ABS01、ABS01、BBS02、BWBS03、ES04、TS05)

以及如何检测仓库中剩余的哪些(零件)数量少于 10,以便我可以打印数量少于 10 的那些?

谢谢你的帮助~

我的文本文件中的内容:
部分:AS 零件 ID:ABS01 从仓库到空调的订单部分:500 仓库中剩余活塞数量:1000
部分:BS 零件编号:BBS02 从仓库订购到刹车部分:600 刹车片 仓库剩余数量:1000
部分:ES 零件编号:ES04 从仓库到发动机的订单部分:100 刹车片仓库中剩余数量:1000
部分:BWS 零件编号:BWBS03 从仓库到车身的订单部分:700 仓库中剩余的门数量:1000
段:TS 零件编号:TS05 从仓库到轮胎的订单段:300 仓库中剩余的门数量:1000
部分:AS 零件 ID:ABS01 从仓库到空调的订单部分:300 仓库中剩余活塞数量:700

try:
    fHand = open("AssemblySecDetails.txt")
    partsDetails = fHand.read()
    print(partsDetails)
    fHand.close()
except:
    print("File Not Found")
    exit()

根据您提供的代码(基本上什么都不做),看看:

对于您的案例和sample.txt

Section: AS Part ID: ABS01 Order from warehouse to aircond section: 500 Piston quantity left in the warehouse: 1000
Section: BS Part ID: BBS02 Order from warehouse to brake section: 600 brakepads quantity left in the warehouse: 1000
Section: ES Part ID: ES04 Order from warehouse to engine section: 100 brakepads quantity left in the warehouse: 1000
Section: BWS Part ID: BWBS03 Order from warehouse to bodywork section: 700 Door quantity left in the warehouse: 1000
Section: TS Part ID: TS05 Order from warehouse to tyre section: 300 Door quantity left in the warehouse: 1000
Section: AS Part ID: ABS01 Order from warehouse to aircond section: 300 Piston quantity left in the warehouse: 700

此代码有效:

import re
with open("sample.txt") as f:
    lines = f.readlines()
ids = [re.search("Part ID: (\w+)",line).group(1) for line in lines]
aux = zip(ids,lines)
aux2 = sorted(aux)
for id,line in aux2:
    print(line,end="")
  • 首先,使用re.searchre group 提取ids
  • 然后,创建zip(ids,lines)辅助值,产生类似[(id1,line1),(id2,line2),...]
  • 然后对其sorted ,在元组的情况下,默认情况下使用第一个项目 ( id ) 进行排序
  • 最后从结果打印line 行在末尾包含换行符,因此使用print(...end="")

单线:

with open("sample.txt") as f:print("".join(sorted(f,key=lambda l:re.search("Part ID: (\w+)",l).group(1))),end="")

编辑到 OP 编辑​​:

根据条件过滤行就像

filteredLines = [line for line in lines if condition(line)]

使用列表理解,其中condition是返回True / False的函数,例如

def condition(line):
    quantity = re.search("quantity left in the warehouse: (\d+)",line).group(1)
    quantity = int(quantity)
    return quantity < 10

再一次,你可以不用re就可以做到,但我认为它没有意义..如果你想学习 python,学习 python 的力量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM