首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python解析文本文件中的文本

用Python解析文本文件中的文本
EN

Stack Overflow用户
提问于 2021-12-13 17:31:47
回答 1查看 243关注 0票数 0

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

代码语言:javascript
复制
Mariam / AI / DS / ML


Steeve / DM / CO / DBMS / ML 

Peter / DS / CO / MDS / ML 

Stella / AI / DS / ML / DSAD 

Martin / AI / ML / DS / MDS 

我的目标是把档案里的每一个字都分开。我为解决这个问题而开发的代码如下所示:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2021-12-13 18:50:26

代码语言:javascript
复制
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(" / ")) 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70338664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档