Python重新匹配:当我的输入是“我有电话”时,如何让我的代码打印出我数据文件中的电话线

2024-04-24 22:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

In my file i have a python code and a text file, however in the text file i have a the words phone and iphone, but when the user input is i have a phone it matches the input with iphone instead of phone. How Do i Solve This Problem? code below:

import re
import string

device = input("What device do you have? ")

device_Array= device.split()


for key_word in device_Array:
    for line in open("Data_file.txt"):
        if key_word in line :
            if re.match(key_word,line):
                phone=input(line[9:])

txt文件片段

Phone  - What type of phone do you have?
phone  - What type of phone do you have?
Apple  - what type of iphone do you have?
apple  - what type of iphone do you have?
Iphone - what model of iphone do you have?
iphone - what model of iphone do you have?

Tags: oftheinyouinputdevicehavetype
1条回答
网友
1楼 · 发布于 2024-04-24 22:18:25

问题可能出在作为re.match参数提供的值中:

给定用户输入“i have a phone”中的关键字,re.match将返回True,因为某些关键字(在本例中为“i”、“phone”)出现在变量line(在本例中为包含“iphone”的行)中。你知道吗

  • 更新:@Jasper是对的-“我”也会匹配“iphone”。相应地编辑了答案(最初我只注意到“phone”是匹配的)。你知道吗

另外,如果您提供代码所使用的文本文件的一个片段,这会有所帮助。这将使事情变得更加清楚。你知道吗

相关问题 更多 >