【问题标题】:Project to return a line in a text file in python from user input项目从用户输入返回python文本文件中的一行
【发布时间】:2014-05-06 17:07:29
【问题描述】:
code = raw_input("Enter Code: ')
for line in open('test.txt', 'r'):
    if code in line:
        print line
    else:
        print 'Not in file'

test.txt 文件如下所示

A        1234567
AB       2345678
ABC      3456789
ABC1     4567890

当输入为 A 时 打印行返回所有带有 A 的行,而不仅仅是第一行。注意:test.txt 文件有大约 2000 个条目。我只想返回包含用户现在输入的数字的行

【问题讨论】:

  • @juanchopanza 我就是这么做的 :)
  • OP:您的代码当前不会运行(您的引号不匹配)。请提供MCVE
  • 好吧,您使用的是in,它检查字符串"A" 是否在行中。为什么你会期望"AB 2345678" 里面没有"A"?它就在那里。在开始时。提示:你可能想要.split()==

标签: python search return raw-input


【解决方案1】:

正如@Wooble 在 cmets 中指出的那样,问题在于您使用 in 运算符来测试等效性而不是成员资格。

code = raw_input("Enter Code: ")
for line in open('test.txt', 'r'):
    if code.upper() == line.split()[0].strip().upper():
        print line
    else:
        print 'Not in file'
        # this will print after every line, is that what you want?

也就是说,可能更好的主意(无论如何取决于您的用例)是将文件拉入字典并改用它。

def load(filename):
    fileinfo = {}
    with open(filename) as in_file:
        for line in in_file:
            key,value = map(str.strip, line.split())
            if key in fileinfo:
                # how do you want to handle duplicate keys?
            else:
                fileinfo[key] = value
    return fileinfo

然后在你全部加载进去之后:

def pick(from_dict):
    choice = raw_input("Pick a key: ")
    return from_dict.get(choice, "Not in file")

并运行为:

>>> data = load("test.txt")
>>> print(pick(data))
Pick a key: A
1234567

【讨论】:

  • OP:你试图编辑我的帖子而不是写评论:)。要将值作为整数获取,只需在它们上调用 int(例如在 def pick 中执行 return from_dict.get(int(choice), "Not in file")
  • 对不起,我是第一次来。并且对python非常陌生。运行脚本时,它确实返回 A 的值,但以下内容也在下一行。 内存问题?
  • @user3609157 value = int(pick(data)) 会将值作为 int 存储在变量 value 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
  • 2012-10-12
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多