【问题标题】:Is it possible to save the print-output in a dict with python?是否可以使用 python 将打印输出保存在字典中?
【发布时间】:2018-03-14 20:25:04
【问题描述】:

我想知道,是否可以将此代码的输出保存到字典中(也许它也是错误的数据类型)。我还没有编码经验,所以我想不出它可以工作的方式。 我想创建一个字典,其中包含 txt.-file 的行以及相应行的值。最后,我想创建一个代码,用户可以选择通过输入在行中搜索单词 - 输出应返回相应的行。有人建议吗?提前致谢!干杯!

filepath = 'myfile.txt'  
with open(filepath) as fp:  
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1

【问题讨论】:

  • 那么你要的是什么?如何搜索文本或如何将文本保存到字典中?

标签: python python-3.x dictionary save output


【解决方案1】:

应该这样做(使用您作为框架提供的代码,只需多行一行即可将其存储在字典中):

my_dict={}

filepath = 'myfile.txt'  
with open(filepath) as fp:  
   line = fp.readline()
   cnt = 1
   while line:
       # print("Line {}: {}".format(cnt, line.strip()))
       my_dict[str(line.strip())] = cnt
       line = fp.readline()
       cnt += 1

然后,您可以像这样提示用户输入:

usr_in = input('enter text to search: ')

print('That text is found at line(s) {}'.format(
                  [v for k,v in my_dict.items() if usr_in in k]))

【讨论】:

  • 这假定您正在输入要搜索的确切句子。这不处理部分搜索,这是我假设 OP 真正想要的。不输入要搜索的确切字符串不会生成任何匹配项,并且代码会抛出 KeyError 异常。
  • 谢谢,但我得到一个错误:第 59 行,在 [v for k,v in line_dict.items() if usr_in in k])) TypeError: argument of类型“int”不可迭代
  • 在您的with open 循环中,尝试将my_dict[line.strip()] = cnt 替换为my_dict[str(line.strip())] = cnt,看看是否有帮助
  • 现在它可以工作了,但我并不总是得到一条线来回报我的投入。工作:输入要搜索的文本:moon 在行中找到该文本[8] 不工作:输入要搜索的文本:dream 在行中找到该文本[]我能以某种方式解决这个问题吗?
  • @StrikeX 为了帮助不区分大小写,通常将搜索查询和文本中的一行都转换为小写,以便在比较之前规范大小写。仅在您搜索时执行此操作,而不是在您实际在字典中输入文本时执行此操作。这样,如果您想显示输入的实际文本,它是真正的文本,而不是转换后的小写形式。将理解中的行替换为:[v for k,v in my_dict.items() if usr_in.lower() in k.lower()]
【解决方案2】:

为了将行字符串值存储为字典中的键和行号作为值,您可以尝试以下操作:

filepath = 'myfile.txt' 

result_dict = {}
with open(filepath) as fp:  
    for line_num, line in enumerate(fp.readlines()):
        result_dict[line.strip()] = line_num+1

或者,使用dictionary comprehension,上面的代码可以是:

filepath = 'myfile.txt' 

with open(filepath) as fp:  
    result_dict = {line.strip(): line_num+1 
                        for line_num, line in enumerate(fp.readlines())}

现在搜索并返回所有带有单词的行:

search_result = [{key: value} for key, value in result_dict.items() 
                                  if search_word in key]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 2018-10-12
    • 2023-04-06
    相关资源
    最近更新 更多