繁体   English   中英

尝试从2个符号之间的txt文件中提取文本并存储在列表中

[英]Trying to extract text from a txt file between 2 symbols and store in a list

编辑:对,所以我的问题的第一部分已经用我在网上找到的这段漂亮的小代码解决了,已对其进行了修改以适应和工作,我现在遇到的问题是制作并阅读创建的列表,我以为我已经使用lst = [lst]列出了该列表,如下面的代码所示。 当我运行下面的代码时,它将从主程序中创建的文件中读取文本,并删除[和]之间的所有内容并将其打印回给我,然后得到此输出... ['47 .660674766635005']

['48 .957947570933946']

['49 .249363925522836']

['37 .88412609655603']

完美,除了似乎所有4个字符串都制成1个列表,并且它不允许我选择单个索引之外,我尝试使用print(lst [0])返回上面的列表,但是如果我将其更改为lst [1]我的索引超出范围。 是否有可能进一步细分列表? 通过手册页尝试了各种具有列表索引的配置,而我已经尝试了所有方法,必须关闭。试图制作列表列表,但仍然存在相同的问题。

因此,在我看来,显而易见的答案是,查找文本文件中找到该字符串的位置,然后将其立即添加到列表中,然后再进行搜索,尝试了一些操作,例如创建新列表并获取代码然后搜索append()到列表,但没有,仍然有问题。

在lst()中尝试x,并将x添加到每个字符串的开头,然后创建一个列表。 我认为此选项可能是最好的,因为要计算出所有mpg的平均值,我需要知道列表中有多少个索引来将其除以。 我只想计算X数即可。这可能是一种更简单的方法,但我不确定。 刚刚阅读了下面链接的json联机帮助页,这似乎是一个不错的选择。 看起来很技术,我将不得不尝试一下

任何线索都请大家

file_path = '/home/jon/Desktop/mpg.txt'

#Open the file in read mode. with operator is used to take care of try..except..finally block.
with open(file_path, "r") as f:
    '''Read the contents of file. Be careful here as this will read the entire file into memory. 
       If file is too large prefer iterating over file object
    '''
    #count=0
    content = f.read()
    size = len(content)
    start =0
    while start < size:
        # Read the starting index of & after the last [ index.
        start = content.find("[",start)
        # If found, continue else go to end of contents (this is just to avoid writing if statements.
        start = start if start != -1 else size
        # Read the starting index of ! after the last ] index.
        end = content.find("]", start)
        # Again, if found, continue else go to end of contents (this is just to avoid writing if statements.
        end = end if end != -1 else size
        '''print the contents between [ and ] (excluding both these operators. 
           If no ! character is found, print till the end of file.
        '''

        lst = content[start+1:end] 
        lst = [lst]
        start = end + 1
        print(lst)

抓着大声笑,我最终会到达那里

============== Original Question Bellow ===========

我编写了一个小程序,可以计算出我的每加仑英里数,并将结果写入文本文件。 可能不是最整洁的代码,但我正在学习,

在def writeToFile()函数中,在将mpg写入文件之前,我已将mpg转换为列表,该程序实际上并未使用该列表,因为我认为这样做可能使提取之间的数据更加容易稍后从txt文件中选择[和]。 在本示例中,您可以从文本文件的输出中看到mpg被[]包围

 Your mpg is...

[37.88412609655603]   

我想做的是通读程序创建的文本文件并在[和]之间复制任何内容。 该控件的定义为averageMiles()的函数,我留下来并注释掉了一些我尝试过的代码,我还尝试了其他一些东西,但是没有任何效果。 我知道我已经接近了,但无法完全了解最后一点,

当我设法读取文本文件并将所有mpg数据提取到一个新列表中时,我将使其求出所有mpg的平均值,并打印到屏幕或文件中,因此数据必须可读。

如果有人能给我一个正确方向的观点,而不是答案,那将是很好的。 我正在使用Python 3.3.2 Ubuntu

import time
import os, sys
GALLON = float(0.219969)
TIME = (time.strftime("%H:%M:%S"))
DATE = (time.strftime("%d/%m/%Y"))
print('enter litres...')
litre = input()
litre = float(litre)
gallonsUsed = litre * GALLON
print('Enter miles')
milesDriven = input()
milesDriven = float(milesDriven)
mpg = milesDriven / gallonsUsed
print('You\'re current mpg is \n  '+str(mpg)+'')
#mpg = [mpg]

def averageMiles():
    file_path = 'mpg.txt'
    with open(file_path, "r") as f: 
        content = f.read()
        size = len(content)
        start =0
        while start < size:
            start = content.find("[",start)
            start = start if start != -1 else size
            end = content.find("]", start)
            end = end if end != -1 else size
            print(content[start+1:end])
            start = end + 1



def checkFile():
    if os.path.isfile('mpg.txt') == True:
        writeToFile()
    else:
        print('File does not exist')
        print('   Making File')
        open("mpg.txt", 'w')
        writeToFile()

def writeToFile():
    file = open("mpg.txt", "r")
    filedata = file.read()
    file.close()

    newLine = " ====================== \n     Your mpg is...\n ---------------------- \n  "+str([mpg])+"   \n ---------------------- \n   Time - "+str(TIME)+" \n   Date - "+str(DATE)+" \n ====================== \n \n" + filedata
    file = open("mpg.txt", "w")
    file.write(newLine)
    #outfile.write("\n".join(mpg))
    file.close()

    file = open("mpg.txt", "r")
    filedata = file.read()
    file.close()
    averageMiles()
    print(filedata)
#averageMiles()
checkFile()

编辑:整理帖子以尝试使问题更清晰,只需再次阅读即可,这没有任何意义

编辑:我想出了如何从文本文件中获取字符串,接下来只需要将其转换成我可以使用的东西,就可以尝试将其转换成列表,然后我可以使用任何数学方法求出平均值mpg。 接下来,我需要学习一些数学。 到目前为止,这是代码,我已经将其添加到了主代码中,到目前为止,所有代码都应按计划运行。感谢您的建议,我将在代码完成后发布其余代码

def averageMiles():
    file_path = 'mpg.txt'
    with open(file_path, "r") as f: 
        content = f.read()
        size = len(content)
        start =0
        while start < size:
            start = content.find("[",start)
            start = start if start != -1 else size
            end = content.find("]", start)
            end = end if end != -1 else size
            print(content[start+1:end])
            start = end + 1

好的,所以在抓了很多头之后,我改变了方法,改而去了

lompg = str('newlist.txt')


mpgList = open(lompg, "r")
listData = mpgList.read()
mpgList.close()
listData=listData.split()
listLength = (len(listData))
data = sum(map(float, listData))
avg = data /listLength
print(avg)

我不是完全想要我想要的东西,但是它可以完成工作,因此我做了一个工作,因此创建了一个单独的文本文件,该文件仅存储mpg数据,然后在计算平均mpg时回读该文件。 如果有人愿意,请在python 3.3.2中运行完成的代码,然后将下面的代码保存到文件中,然后将cd保存到位置文件中,然后python3'filename.py'程序创建的所有文件都将在该位置中创建

import time
import os
outfile = 'mpgoutput.txt' # record of mpg results
infile = 'mpglist.txt' # list of all mpg to calculate avg
GALLON = float(0.219969) # 1 litre, used to calculate litres into gallons
TIME = (time.strftime("%H:%M:%S"))
DATE = (time.strftime("%d/%m/%Y"))
print('enter litres...')
litre = input()
litre = float(litre)
gallonsUsed = litre * GALLON # work out litres into gallons
print('Enter miles')
milesDriven = input()
milesDriven = float(milesDriven)
mpg = milesDriven / gallonsUsed # mpg calculated
if os.path.isfile(infile) == False: # check if file exists if not create it
     print('File does not exist')
     print('   Making File')
     open(infile, 'w')
mpglistread = open(infile, "r") 
originalList = mpglistread.read()
mpglistread.close()
mpglistwrite = open(infile, "w")
mpglistwrite.write(''+str(mpg)+'\n' + originalList) 
mpglistwrite.close()
mpgList = open(infile, "r")
listData = mpgList.read()
mpgList.close()
listData=listData.split()
listLength = (len(listData))
data = sum(map(float, listData))
avg = data /listLength

def checkFile():
    if os.path.isfile(outfile) == True:
        readFile()
    else:
        print('File does not exist')
        print('   Making File')
        open(outfile, 'w')
        readFile()

def readFile():

    file = open(outfile, "r")
    filedata = file.read()
    file.close()
    newLine = " ====================== \n     Your mpg is...\n ---------------------- \n  "+str([mpg])+"   \n ---------------------- \n   Time - "+str(TIME)+" \n   Date - "+str(DATE)+" \n ====================== \n \n" + filedata
    file = open(outfile, "w")
    file.write(newLine)
    file.close()
    file = open(outfile, "r")
    filedata = file.read()
    file.close()
    print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n') 
    print(" ====================== \n     Your mpg is...\n ++++++++++++++++++++++ \n  "+str([mpg])+"   \n ---------------------- \n Your average mpg is...\n ++++++++++++++++++++++ \n  "+str(avg)+"   \n ---------------------- \n   Time - "+str(TIME)+" \n   Date - "+str(DATE)+" \n ====================== \n \n")

checkFile()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM