簡體   English   中英

將文本文件的特定 int 行讀取並獲取到 python 上的變量中

[英]read and get specific int line of the text file into variable on python

a_file = open('file.txt')
string = 'a word'
flag = 0
index = 0
for line in a_file:
    index += 1
    if string in line:
      break
index -= 1

lines_to_read = [index]

for position, line in enumerate(a_file):
    if position in lines_to_read:
        file = line
print(line)

我找到了'a word'所在的行,我想把這些行變成一個變量

但它只讀取文本文件的第一行

我該如何解決

@Maicon 有它,盡管在 python 中你甚至不需要全局變量,你可以在if語句中創建和設置desired_line ,它的命名空間將擴展到包含if語句的整個 function :

a_file = open('file.txt')
string = 'a word'
for line in a_file:
    if string in line:
        desired_line = line
        break

print(desired_line)

a_file.close()

您可以做的是檢查行中的字符串。 這會為你做的。

a_file = open('all.txt')
string = 'a word'
flag = 0
index = 0
for position, line in enumerate(a_file): 
    if string in line: #=== if 'a word' in line
        file = line
        pos=position+1
        break
print(file,"Line Number: ",pos)

但是,如果存在更多相同的單詞,您可以使用dict來獲取行號和值。

a_file = open('all.txt')
string = 'f'
dictionary={}
flag = 0
index = 0

for position, line in enumerate(a_file): 
    if string in line:
        file = line
        pos=position
        dictionary.update({pos+1:[file.strip("\n").strip(),file.count(string)]})
if dictionary!={}:
    print("\n------- Statistics --------\n")
    print("Total Items found: ",len(dictionary),"\nTotal Occurences: ",sum([dictionary.get(x)[1] for x in dictionary]))) #=== Get the sum of all numbers

    for key, value in dictionary.items():
        print("-------------------------")
        print("Line: "+value[0],"\nNumber of occurrences: ",value[1],"\nLine Number: ",key)
        
else:
    print("Oops. That word was no found. Check you word again.")

您可以簡單地遍歷這些行,並將該行分配給先前創建的字符串變量,如果滿足條件,則該字符串出現在文件的一行中:

a_file = open('file.txt')
string = 'a word'
res_line = ""

for line in a_file:
    if string in line:
        res_line = line

print(res_line)

a_file.close()

您還可以創建一個列表,其中包含字符串出現的每一行:

a_file = open('file.txt')
string = 'a word'

res = [line for line in a_file if string in line]
print(res)

a_file.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM