【问题标题】:Parse A Text In A Text File With Python使用 Python 解析文本文件中的文本
【发布时间】:2022-01-17 03:53:14
【问题描述】:

我使用“/”特殊字符来分割文本文件中的每个单词。代码输出如下:

Mariam / AI / DS / ML


Steeve / DM / CO / DBMS / ML 

Peter / DS / CO / MDS / ML 

Stella / AI / DS / ML / DSAD 

Martin / AI / ML / DS / MDS 

我的目标是分隔文件中的每个单词。我为解决这个问题而开发的代码如下:

import os

desktop = os.path.join(os.path.expanduser("~"), "Desktop")
filePath = os.path.join(desktop, "inputPS13.txt")
file2 = open(filePath)
line1=file2.readline()
print("file is opened")

while(line1!=""):
    print(line1)
    line1=file2.readline()
   
for line in file2:
    for word in line.split("/"):
           print(word)

【问题讨论】:

    标签: python file string-parsing


    【解决方案1】:
    with open("input.txt", "r") as file:
    
        # read file and remove new line characters
        lines = [line.strip() for line in file.readlines()]
    
        # remove empty strings
        lines = [line for line in lines if not line == ""]
    
    for line in lines:
    
        # prints a list of of every word in a line
        print(line.split(" / ")) 
    

    【讨论】:

      猜你喜欢
      • 2012-08-09
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多