Python 搜索.txt中的所有字符串
我试着运行一个程序来查看一个.txt文件,如果,否则取决于内容 我想会的Python 搜索.txt中的所有字符串,python,if-statement,string-search,Python,If Statement,String Search,我试着运行一个程序来查看一个.txt文件,如果,否则取决于内容 我想会的 Searhterms = [A, B] with('output.txt') as f: if ('A' and 'B') in f.read(): print('mix') eLif ('A') in f.read: if ('B') not in f.read: print('ONLY A') elif ('B') in f.read()
Searhterms = [A, B]
with('output.txt') as f:
if ('A' and 'B') in f.read():
print('mix')
eLif ('A') in f.read:
if ('B') not in f.read:
print('ONLY A')
elif ('B') in f.read():
if ('A') not in f.read:
print('ONLY B')
else:
if ('A' and 'B') not in f.read:
print('NO AB)
但是,如果A和B出现,它会工作,但如果只有一个,它会跳到另一个。我越看越糊涂。如评论中所述,
f.read()
一次性读取文件的所有内容,因此后续调用f.read()
不会返回任何数据。您需要将数据存储在变量中。此外,您还误解了和操作符的工作原理
with open('output.txt', 'r') as f:
data = f.read()
if 'A' in data and 'B' in data:
print('mix')
elif 'A' in data:
print('ONLY A')
elif 'B' in data:
print('ONLY B')
else:
print('NO AB)
你最好用这个:
Searhterms = [A, B] # not sure why you need this
with('output.txt') as fin : # nice name for the INPUT file, btw
lines = fin.readlines()
for line in lines :
if ('A' in line) and ('B' in line):
print('mix')
eLif 'A' in line: # nice uppercase 'L', will puzzle the python
#if 'B' not in line: # don't need this
print('ONLY A')
elif 'B' in line:
#if 'A' not in line: # don't need this
print('ONLY B')
else:
#if ('A' and 'B') not in f.read: # this condition is not required
print('NO AB')
if len(lines) == 0 :
print('empty file')
我同意这里的扎比尔·阿尔·纳粹主义。
read f.read()清空文件
用这个
Searhterms = ['A', 'B']
with open('output.txt') as f:
content = f.read()
if ('A' and 'B') in content:
print('mix')
elif 'A' in content:
if 'B' not in content:
print('ONLY A')
elif 'B' in content:
if 'A' not in content:
print('ONLY B')
else:
if ('A' and 'B') not in content:
print('NO AB')
你的代码有点问题。
首先,您应该只调用f.read()
一次。
你的if语句是错误的
尝试以下代码并对其进行分析:
with open('output.txt') as f:
lines = f.read()
if 'A' in lines and 'B' in lines:
print('mix')
elif 'A' in lines:
print('ONLY A')
elif 'B' in lines:
print('ONLY B')
else:
print('NO AB')
f、 read()在您第一次使用它时会清空。您可以建议其他方法吗?您可以将读取的内容放入变量中并进行检查?非常感谢,但有一个问题。如果我的output.txt文件为空,则不会打印“NO AB”,但如果其中包含随机数,则会打印。如果output.txt为空,是否有办法将其打印出来?效果非常好!你是个明星对不起!我以为一切都搞定了。如果文件为空,则打印“空文件”,但如果文件不是空文件,则现在打印混合空文件,并将空文件粘贴在everything@Smellegg修正了,抱歉