![](/img/trans.png)
[英]I coded my telegram bot (in python) prompting user to send an image. How do I make sure users only send image and nothing else?
[英]Python - How to make sure that a line being read from a file contain only a given string and nothing else
為了確保我准確地開始和停止閱讀文本文件,我在文本文件之間提供“ start1” <->“ end1”,“ start2” <->“ end2”作為標簽,並提供那到我的python腳本。 在我的腳本中,我將其讀取為:
start_end = ['start1','end1']
line_num = []
with open(file_path) as fp1:
for num, line in enumerate(fp1, 1):
for i in start_end:
if i in line:
line_num.append(num)
fp1.close()
print '\nLine number: ', line_num
fp2 = open(file_path)
for k, line2 in enumerate(fp2):
for x in range(line_num[0], line_num[1] - 1):
if k == x:
header.append(line2)
fp2.close()
在我到達start10 <-> end10之前,這一直很好。 例如。 它檢查行中是否包含“ start2”,並讀取包含“ start21”的文本,以及結束標記的類似內容。 因此提供“ start1,end1”作為輸入也將讀取“ start10,end10”。 如果我替換行:
if i in line:
同
if i == line:
它拋出一個錯誤。
如何確保腳本讀取僅包含“ start1”而不包含“ start10”的行?
import re
prog = re.compile('start1$')
if prog.match(line):
print line
如果沒有匹配項,則應返回None;如果該行與已編譯的正則表達式匹配,則應返回一個正則表達式匹配對象 。 正則表達式末尾的“ $”表示該行的末尾,因此“ start1”有效,但“ start10”無效。
或其他方式
def test(line):
import re
prog = re.compile('start1$')
return prog.match(line) != None
> test('start1')
True
> test('start10')
False
您可能想研究正則表達式。 Python re庫具有一些很好的正則表達式工具。 它可以讓您定義一個字符串以與行進行比較,並且可以檢查行的開始和結束。
由於標記始終位於行尾,因此請更改:
start_end = ['start1','end1']
至:
start_end = ['start1\n','end1\n']
如果可以控制輸入文件,請考慮在每個標簽的末尾添加下划線(或任何非數字字符)。
'啟動1 _'< - > 'end1_'
'start10 _'< - > 'end10_'
其他答案中提供的正則表達式解決方案更為優雅,但需要使用正則表達式。
您可以使用find()
做到這一點:
for num, line in enumerate(fp1, 1):
for i in start_end:
if i in line:
# make sure the next char isn't '0'
if line[line.find(i)+len(i)] != '0':
line_num.append(num)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.