Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

How to read from a text file and find out which row has the integer value of lesser than a certain assigned value in python?

This text file is AssemblySecDetails.txt

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

I am trying to find out which Part ID has the quantity of lesser than 10

fHand = open("AssemblySecDetails.txt", 'r')
partsDetails = fHand.readlines()
    def condition(parts):    
        filteredLines = [parts for parts in partsDetails if condition(parts)]
        quantity = re.search("quantity left in the warehouse: (d+)", parts).group(1)
        quantity = int(quatity)
        return quantity < 10
    condition(parts)

output UnboundLocalError: local variable 'parts' referenced before assignment

What is the mistake in my code and how should I call the function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have a look at how list comprehension works. Just read the data from file and comprehend them with the beforhend (or inline) defined condition:

def condition(parts): # using re module
    import re
    quantity = re.search("quantity left in the warehouse: (d+)", parts).group(1)
    quantity = int(quantity)
    return quantity < 10

def condition(parts): # or if quantity is always 18th word
    quantity = parts.split()[17]
    quantity = int(quantity)
    return quantity < 10

# read lines
with open("AssemblySecDetails.txt") as f:
    partsDetails = f.readlines()
#filter lines
filteredLines = [parts for parts in partsDetails if condition(parts)]
# print lines
for line in filteredLines: print(line,end="")

Oneliner:

with open("AssemblySecDetails.txt") as f: print("".join(line for line in f if int(line.split()[17])<10),end="")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...