對于給定的文本檔案(sample.txt),我想根據該行(索引)上存在的字串獲取索引值。
示例檔案包含以下文本 (sample.txt):
第 1 行:打開一個檔案。
第 2 行:讀取檔案并將其存盤在變數中。
第 3 行:使用“in”運算子檢查檔案中是否存在字串的條件。
第 4 行:如果條件為真,則列印找到字串的索引。
第 5 行:關閉檔案。
如果我的目標字串是“變數”。我想要的輸出是:2
uj5u.com熱心網友回復:
這應該這樣做:
def indicesOfQueryOnFile(query, file):
with open(file, 'r') as f:
cleanLines = [line for line in f.readlines() if len(line.strip()) > 0]
indices = [i 1 for i, line in enumerate(cleanLines) if query in line]
return indices
對于文本檔案:
line 1: open a file.
line 2: Read a file and store it in a variable.
line 3: check condition using ‘in’ operator for string present in the file or not.
line 4: If the condition true print the index in which the string is found.
line 5: Close a file.
another line with variable
它會輸出:
indicesOfQueryOnFile('variable', 'test.txt')
# [2, 6]
uj5u.com熱心網友回復:
如果我理解正確,那么您可能正在尋找這樣的東西。
def FindLineIndexOfFile(file, text):
file = open(file, "r")
line_count = 0
for lines in file.readlines():
line_count = 1
line_index = lines.strip()
if line_index == text:
file.close()
return line_count
index = FindLineIndexOfFile("sample.txt", "hello world")
print(index)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405541.html
標籤:
