python 包含几个指定字符串_Python:在包含多个列的文本文件中搜索特定的字符串...

我有一个用制表符分隔的文本文件(每个列都负责某个组件):1 (who?) 2 (age) 3 (Does what?) 4 )(where lives?)

A Dog 4 Walks Lives in a box

B Parrot 2 Eats Lives in a cage

C Cat 3 Sleeps Lives in a house

用户必须在两个选项中选择一个来查找关于动物的所有信息。用户可以在第一列或第四列输入猜测:

^{pr2}$

或者4=Live in a box**

如果有匹配的,它会打印出整条线。在在第一种情况下,如果用户决定使用第一列(谁?)在中查找有关动物的信息将显示:Cat 3 Sleeps Lives in a house

在第二种情况下,如果用户决定使用第四列(where lives?)在中查找有关动物的信息将显示:Dog 4 Walks Lives in a box

我需要的是找到一个合适的函数来搜索动物。我尝试使用search()和match()但没有用。在**EDIT after codesparkle's advice**

我似乎无法将建议的功能集成到我的程序中。我对第[column-1]行位特别困惑。我试着“玩”这个函数,但是我没有想出任何有用的东西。这是我需要完成的真正的代码。在while True:

try:

OpenFile=raw_input(str("Please enter a file name: "))

infile=open(OpenFile,"r")

contents=infile.readlines()

infile.close()

user_input = raw_input(str("Enter A= for animal search or B= for place of living search: \n"))

if user_input.startswith("A="):

def find_animal(user_input,column):

return next(("\t".join(line) for line in contents

if line[column-1]==user_input),None)

find_animal(user_input[1:])

print str((find_animal(user_input[1:], "WHO?"))) # I messed up the first time and gave numeric names to the columns. In reality they should have been words that indicate the proper name of the column. In this case it is WHO- the first column which signifies the animal.

else:

print "Unknown option!"

except IOError:

print "File with this name does not exist!"

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值