【问题标题】:Python read text file into an array of words [duplicate]Python将文本文件读入单词数组[重复]
【发布时间】:2023-03-03 09:00:24
【问题描述】:

为了学习 Python,我正在尝试构建一个对文件进行拼写检查的应用程序。 我看到 SpellChecker 库在其最基本的用法中验证来自已知/未知单词数组的单词:

from spellchecker import SpellChecker

spell = SpellChecker()
spell['morning']  # True
'morning' in spell  # True

# find those words from a list of words that are found in the dictionary
spell.known(['morning', 'hapenning'])  # {'morning'}

# find those words from a list of words that are not found in the dictionary
spell.unknown(['morning', 'hapenning'])  # {'hapenning'}

由于我想验证整个文件,我想添加一个函数来读取文本文件并将其转换为要检查的单词数组:

def readFile(fileName):
    fileObj = open(fileName, "r")  # opens the file in read mode
    words = fileObj.read().splitlines()  # puts the file into an array
    fileObj.close()
    return words

不幸的是,上面的函数将整行(而不是单个单词)放入数组中。 我试过了:

words = fileObj.read().splitlines().split() 

但是 split() 不能应用于 splitlines() 函数。 知道如何实现吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    你必须在每一行调用 split()。

    words = []
    lines = fileObj.read().splitlines()
    for line in lines:
        words.extend(line.split())
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2016-04-23
      • 2018-07-11
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      • 2019-12-10
      • 2019-07-03
      • 2018-02-02
      相关资源
      最近更新 更多