【问题标题】:Splitting words in different lines to a list in Python将不同行中的单词拆分为Python中的列表
【发布时间】:2021-09-09 15:04:39
【问题描述】:

我有一个文本文件,其文本为:

Hello All,

Hope you are enjoying learning Python
We have tried to cover every point in detail to avoid confusion
Happy Reading

我想将每个单词分成以下格式的列表, ['Hello','All,','Hope','you','are','enjoying','learning','Python','We','have','tried','to', '覆盖','每个','点','in','细节','to','避免','困惑','快乐','阅读。 我已经尝试了下面的代码,它正在工作,但唯一的问题是输出进入双方括号并在一个新行中,如下所示

words = [open('example.txt').read().split()]
words

[['你好', '全部,', '希望', '你', '是', '享受', '学习', 'Python', '我们', '有', '尝试', '到', '覆盖', '每一个', '观点', '在', '细节', '到', '避免', '困惑', '快乐的', '读']] 我是 python 和学习的新手。如果有人可以帮助我,那将有很大帮助。我希望输出在单个方括号中并继续。

【问题讨论】:

    标签: list file-handling


    【解决方案1】:
    words = open('example.txt').read().split()
    print(words)
    

    只需删除括号。

    或者如果你必须使用旧代码,你可以使用 words[0]。

    【讨论】:

    • 以及如何将它们放在同一行?
    • 什么意思,拆分后,words只是一个单词列表。
    • 你的意思是打印(字),那么它在同一行
    • word[0] 在这里是什么意思?
    • 您的原始代码将拆分输出放在外部[]的列表中,这就是为什么您必须使用[]层的原因。 words[0] 只是选择列表中的唯一元素。
    猜你喜欢
    • 2021-11-01
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2010-09-11
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    相关资源
    最近更新 更多