如果文件中存在另一个字符串的字符串,如何检入文件?

时间:2016-06-21 20:09:32

标签: python

如果字符串存在并且旁边有一些字符串,如何检入文件。 确切地说,我有以下代码:

with open ('CTF.txt', 'r') as myfile:
        strings = (validationforvote, "voted")
            for line in myfile:
               if any(s in line for s in strings):
                print "you cannot vote twice"
myfile.close()

我在validationforvote(变量)中存储四位数字,并且想要检查它在文件中的validationforvote旁边有一个带有“voteed”的字符串。目前我已经存档:

9779 voted
8568 voted

如果我再次输入9779作为validationforvote,它必须在此文件中搜索是否存在以及旁边是否有“已投票”。如果是的话,它必须告诉用户,你不能投两次。 目前模式代码未执行,因为它应该是:

4 个答案:

答案 0 :(得分:0)

您可以尝试使用正则表达式操作:

import re
with open ('CTF.txt', 'r') as myfile:
    result=re.search(str(validationforvote)+' voted$', myfile.read())
    if result:
        print "you cannot vote twice"
    myfile.close()

答案 1 :(得分:0)

你有一些问题。

  

首先,您的if语句正在检查行中是否validationforvotevoted,这会阻止您的代码按预期运行。

     

其次,如果您使用with open(...) as myfile打开文件,则不必在阻止后关闭它。

     

第三,使用元组来存储validationforvote和文字'voted'有点不必要。

清理一下,你可以使用以下内容:

with open ('CTF.txt', 'r') as myfile:
    for line in myfile:
        if line.strip() == "{} voted" % (validationforvote):
            print "you cannot vote twice"

答案 2 :(得分:0)

如果您的数据结构与您的示例相同,则可以执行以下操作:

with open("myfile") as open_file:  
    # read the file and split it on each newline
    f=open_file.read().split('\n')

for line in f:
    # check if any of the lines start with validationforvote
    # and has allready voted  
    if validationforvote == line[:4] and 'voted' == line[5:]:
        print("You cannot vote twice!")
        break

答案 3 :(得分:-1)

目前,如果 在线 - 这意味着每次投票'在那里,它打印。你的条件应该更像是:

if (" ".join(strings) in line):

所以它构建了你正在寻找的东西,即"9779 voted"作为要查找的确切字符串,然后看看是否在行中(你也可以这样做==,但是你必须考虑换行符)