【问题标题】:How to extract information from a txt(RIS) file in flask如何从烧瓶中的 txt(RIS) 文件中提取信息
【发布时间】:2020-04-13 14:55:15
【问题描述】:

我的文件在文本编辑器中看起来如下:

Firstname  - phil
Lastname  - taylor
Birthdayyear  - 1956
Country  - england
END  -

我将文件存储在我的python变量txtFile中,当我使用print(txtFile.read())打印文件时,它在控制台中如下所示:

b'Firstname  - phil\r\nLastname  - taylor\r\nBirthdayyear  - 1956\r\nCountry  - england\r\nEND  - '

现在我需要获取名字、姓氏、生日年份和国家,并将这些信息存储在变量中,以便以后可以访问这些信息。

例如,当我print("His first name is " + firstName) 时,我会在控制台中得到His first name is phil

txt 文件的架构并不总是相同的。 “Firstname”、“Lastname”、“Birthdayyear”和“Country”等名称总是相同的,但它们的顺序并不总是相同。因此,例如“Country”可能是第一行,“Firstname”是最后一行。

我还没有发现与我在 stackoverflow 上的问题相同的问题,所以也许有人可以帮助我解决这个问题。

非常感谢

【问题讨论】:

    标签: python file flask file-read


    【解决方案1】:

    我终于找到了解决问题的方法。我不知道,这是否是最好的方法,但它对我有用:

    首先,我浏览了 txt 文件的每一行并将每一行添加到一个数组中。然后我 当行中有" - " 时,拆分数组的每一行。例如,这会将每一行从["Firstname - phil"] 拆分为["Firstname","phil"],然后如果您遍历数组的每一行并发出if 请求,您就可以访问该名称:如果该行的第一个元素等于"Firstname",将您的 firstName 变量设置为等于该行的第二个元素。我不知道这是否可以理解,但这就是它在 python 代码中的样子...... :-D

     txtFileToArray = []
     splittedTxtArray = []
     firstName=""
    
         #go through every line of the text file
         for line in txtFile:
    
              #put every line at the end of the array txtFileToArray and delete the "b" (binaray) at the beginning of every line
              txtFileToArray.append(line.decode('utf-8'))
    
        #then go through every line of the array and split every line when there is a "  - " and store the lines in a new array
         for line in txtFileToArray: 
    
              splittedTxtArray.append(element.split("  - "))
    
        #then check every line of the splitted array if there is a Firstname at the first position
        for linein splittedTxtArray:
    
              if(line[0] == "Firstname"):
                 firstName= line[1]
    

    希望有一天能帮到你:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 2022-01-18
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 2021-12-05
      • 2015-05-24
      相关资源
      最近更新 更多