在python

时间:2017-07-01 15:33:05

标签: python text

我有一个包含以下字词的文本文件:“ak”,“bh”,“cd”,“dfg”。
现在在Python中如何找到单词'df'是否存在?

我的代码:

filename =raw_input("Enter the new Shop Name: ")
cs =open('shopname.txt','r')
for line in cs.readlines():
    if re.search(filename, line, re.I):
        print "Already Exists!!"

文本文件是: Image of the txt file。 现在,如果我将输入设为'df',则表明该单词存在。但我不想表明这一点。 我希望它具体而且区分大小。

3 个答案:

答案 0 :(得分:1)

假设每个商店名称都在单独的行中。

filename =raw_input("Enter the new Shop Name: ")

cs =open('shopname.txt','r')

for line in cs.readlines():
    if re.match(filename + '$', line, re.I):
        print "Already Exists!!"

re.search搜索一行/一行。改为使用匹配

答案 1 :(得分:0)

你正在过度思考这个问题。您可以使用in搜索该特定字词:

filename =raw_input("Enter the new Shop Name: ")

cs = open('shopname.txt','r')

for line in cs.readlines():
    if 'df' in line:
        print "Already Exists!!"

我也纠正了你的错误(可能只是一个复制粘贴问题)。您在if条件结束时错过了冒号。

更多情况下,如果您只是寻找一个sepparate df字词,则可以提供this regex a try

  

\ b匹配空字符串,但仅限于a的开头或结尾   字。

请注意,re模块使用" word"的简单定义。作为"字母数字或下划线字符的序列",其中"字母数字"取决于区域设置或unicode选项。

更多信息,建议您在处理文件时使用with(),因为它会为您处理一些事情(例如:它会自动关闭)你的文件)

with open('shopname.txt') as cs:  # this will close the file for you as well
    for line in cs:  # you don't need to use readlines here
        if re.search(r'\bdf\b', sentence):
            print('True')

答案 2 :(得分:0)

这很完美......你应该在每一行新行中都有商店名称

filename =raw_input("Enter the new Shop Name: ")
check =open('shopname.txt','r')
file=filename+"\n"   #CODE MODIFIED HERE
for line in check.readlines():
    if line.find(file)>=0:         #CODE ALSO MODIFIED HERE
        print "Already Exists!!"
    else:
        print ""
相关问题