python字典输出保存_是否可以使用python将打印输出保存在字典中?

I want to know, if it's possible to save the output of this code into a dictionary (maybe it's also the wrong data-type). I'm not expirienced in coding yet, so I can't think of a way it could work.

I want to create a dicitionary that has the lines of the txt.-file in it alongside the value of the corresponding line. In the end, I want to create a code, where the user has the option to search for a word in the line through an input - the output should return the corresponding line. Has anyone a suggestion? Thanks in advance! Cheers!

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

解决方案

This should do it (using the code you provided as a framework, it only takes one extra line to store it in a dictionary):

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

Then, you can prompt for user input like this:

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]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值