我有一個輸出文本文件,我只想要151行中的數字13.0如何在python中讀取txt文件中特定位置的數字號碼?
13.0 = ebeam1!在GeV的
束1的總能量與74.761227線479
#集成重量(PB):74.761227
我不知道如何讀這些數字,並把它們寫在另一個文件中的行?
我有一個輸出文本文件,我只想要151行中的數字13.0如何在python中讀取txt文件中特定位置的數字號碼?
13.0 = ebeam1!在GeV的
束1的總能量與74.761227線479
#集成重量(PB):74.761227
我不知道如何讀這些數字,並把它們寫在另一個文件中的行?
您想要使用linecache模塊。
import linecache
line = linecache.get('path/to/file', 479)
然後將其寫入另一個文件。
with open('other/file.txt', 'w') as f:
f.write(line)
假設你想只提取的行號部分:
import re
In [4]: re.search(r'(\d+.*\d*$)', line).group()
Out[4]: '74.761227'
科裏勁爆的回答會的工作,但如果你不知道你正在尋找的行是什麼號碼你可以這樣做:
import re
regex = re.compile(r"# Integrated weight \(pb\) : (?P<number>-?\d+\.?\d*)")
with open(file_path, "r") as lines:
for line in lines:
match = re.match(regex, line)
if match:
number = float(match.group("number"))
return number
感謝上帝,你的問題,你會基本上通過文件中的行用一個for循環中循環,並在每行添加到列表中。因此,無論何時,您都可以用您想要的行號呼叫清單,並將該特定行發送給您。然後將它保存在一個變量中,然後對其應用正則表達式(正則表達式),以僅獲取浮點數。
例如TXT文件:
151 Jesus 13.0
152 John
153 Peter 74.745392
然後在你的Python文件
import re
file_line_arr = []
with open('example.txt', 'r') as file:
for line in file:
file_line_arr.append(line)
line_1 = file_line_arr[151-1]
line_3 = file_line_arr[153-1]
first_number = re.findall('\d+.?\d+', line_1)
second_number = re.findall('\d+.?\d+', line_3)
first_number_wq = re.sub("'", "", str(first_number))
first_number_wb = re.sub('(\[|\])', '', first_number_wq)
second_number_wq = re.sub("'", "", str(second_number))
second_number_wb = re.sub('(\[|\])', '', second_number_wq)
with open('new_file.txt', 'w') as new_file:
new_file.write(first_number_wb + '\n' + second_number_wb)
這是一本關於蟒蛇,你會很喜歡 - (dive into python3)進行搜索
嗨,@ surge10!歡迎來到StackOverflow。您可能需要在編輯器中的每行之前至少添加四個空格,或者突出顯示並單擊「{}」按鈕,以便在答案中格式化代碼。它會幫助他人理解你在說什麼! – PaSTE
import linecache
import re
ln = linecache.getline('so_qn_test_file.txt', 479)
nums = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", ln)
# print(nums)
with open('op_file.txt','w') as f:
f.write(','.join(nums))
這將工作。我已經測試過了。 有關正則表達式的解釋,this應該有所幫助。
不知道你在找什麼作爲答案。但是您可以查看RegEx語言集。它內置到python中,用於解析字符串。 (https://regex101.com/) – MaylorTaylor