社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

只读文本文件python中指定行中的数字

Rachel • 5 年前 • 1658 次点击  

我试着从一个文本文件的第18行和第19行中读取两个浮点数并求出它们的平均值。请只看由 ######### 是的。

这个文件是单词和数字的混合体,我不知道怎么读这些数字。第18行和第19行的示例如下:

TM-score= 0.27878 (if normalized by length of Chain_1)
TM-score= 0.36068 (if normalized by length of Chain_2)
def tmval(self,name,tmvalpath):
    dir = tmvalpath
    splits = []
    avg = 0
    number1 = 0
    number2 = 0
    for f in os.listdir(dir):
        file_name2, file_ext = os.path.splitext(f)
        n1,n2,align = file_name2.split('_')
        n = ('{}_{}'.format(n1,n2))
        if n == name:
#####################################################
            with open(os.path.join(dir,f)) as file:
                for i, line in enumerate(file):
                    if i == 17:
                       #retrieve data from 18th line
                       number1 =
                    elif i == 18:
                       # retrieve data from 19th line
                       number2 = 
######################################################
  avg = float(number1 + number2)/2                      
  return avg
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46872
 
1658 次点击  
文章 [ 2 ]  |  最新文章 5 年前
mlotz
Reply   •   1 楼
mlotz    5 年前

看起来像是正则表达式的作业。

像[0-9][.][0-9]*这样的东西应该能做到。

蟒蛇:

import re
import numpy as np

line = 'TM-score= 0.36068 (if normalized by length of Chain_2)'

str = re.search(r'[0-9][.][0-9]*', line)
number1 = float(str.group(0))
print(number1)
gmds
Reply   •   2 楼
gmds    5 年前

可以使用正则表达式:

import re

with open(os.path.join(dir,f)) as file:
    for i, line in enumerate(file):
        if i == 17:
            number1 = float(re.search(r'\d+\.\d+', line).group())

        elif i == 18:
            number2 = float(re.search(r'\d+\.\d+', line).group())