简体   繁体   English

我如何让 python 在文件中查找范围?

[英]How would I make python look for a range in a file?

I am trying to make python open a file, and return all lines where POINTBALANCE = <value> is in the given range我试图让 python 打开一个文件,并返回POINTBALANCE = <value>在给定范围内的所有行

num = input("Points to check: ")
num2 = num + str(100)

with open("glist.txt") as search:
    for line in search:
        if "POINTS BALANCE = " + num <= num <= num2 in line:
            print(line)

I want it to be so that if I input 100 in num that python automatically checks for POINTSBALANCE - with 100 to 200 and then when I put 200 in num i want it to check for 200 to 300我希望它是这样的,如果我在num中输入100 ,python 会自动检查POINTSBALANCE - 100200 ,然后当我在num输入200 ,我希望它检查200300

You might want to try extracting the number from the line (if POINTSBALANCE = exists) using a regular expression.您可能想尝试使用正则表达式从行中提取数字(如果POINTSBALANCE =存在)。 Without example data it is bit of a guessing game and making assumptions, but for inspiration:没有示例数据,这有点像猜谜游戏和做出假设,但可以从中获得灵感:

import re

num = int(input("Points to check: "))
delta = 100

pattern = 'POINTSBALANCE = (\d+)'
with open("glist.txt") as search:
    for line in search:
        regex = re.search(pattern, line)
        if regex and num <= int(regex.group(1)) <= num + delta:
            print(line)

As already was pointed out in some comments you should cast integer strings to int to compare them with numbers.正如一些评论中已经指出的那样,您应该将整数字符串转换为 int 以将它们与数字进行比较。

Python's strings offer enough convenient functions to achieve your task here, namely Python 的字符串提供了足够方便的函数来完成这里的任务,即

str.startswith(substring) - self explaining str.startswith(substring) - 自解释
str.split() - creating a list of substrings, by default split at spaces str.split() - 创建一个子字符串列表,默认在空格处分割
str.strip() - remove unwanted characters at beginning and end str.strip() - 在开头和结尾删除不需要的字符

So your code could be changed to所以你的代码可以改为

num = int(input("Points to check: "))
num2 = num + 100

with open("glist.txt") as search:
    for line in search:
        if line.startswith("POINTS BALANCE = "):
            x = int(line.split('=')[-1].strip())
            if  (num <= x) and (x <= num2):
                print(line)

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

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