python - 如何修改我的函数以使用列表理解?

标签 python python-3.x list-comprehension

特别是从这个 getwords 函数中删除停止字母时。

def getwords(fileName):
  file = open(fileName, 'r')
  text = file.read()
  stopletters = [".", ",", ";", ":", "'s", '"', "!", "?", "(", ")", '“', '”']
  text = text.lower()
  for letter in stopletters:
   text = text.replace(letter, "")
  words = text.split()
  return words 

对于这个双字母函数中的循环

def compute_bigrams(fileName):
  input_list = getwords(fileName)
  bigram_list = {}
  for i in range(len(input_list) - 1):
    if input_list[i] in bigram_list:
      bigram_list[input_list[i]] = bigram_list[input_list[i]] + [input_list[i + 1]]
    else :
     bigram_list[input_list[i]] = [input_list[i + 1]]
  return bigram_list

最佳答案

你可以这样重写它:

def getwords(file_name):
    with open(file_name, 'r') as file:
        text = file.read().lower()

    stop_letters = (".", ",", ";", ":", "'s", '"', "!", "?", "(", ")", '“', '”')
    text = ''.join([letter if letter not in stop_letters else '' for letter in text])

    words = text.split()
    return words

我使用上下文管理器打开文件,合并一些行(不需要为 .lower() 设置特殊的行)并使用列表理解来遍历文本并添加字母,但前提是字母不在 stop_letters 中。加入该列表后,您会得到相同的结果。

请注意,您也可以使用生成器表达式,这会更好:

text = ''.join((letter if letter not in stop_letters else '' for letter in text))

如果你真的想保存那一行,你可以这样做:

返回 text.split()

关于python - 如何修改我的函数以使用列表理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59229469/

相关文章:

python - Numpy 数组获取不是 NaN 的数组的子集/切片

python - 计算 Pandas 数据框中相似值的百分比

python - 如何在多个条件下更新值

python - 如何让游戏按钮显示在基于Python的四子棋游戏中?

python - 将 Pydantic 模型传递给另一个模型时复制

python - 列表理解的优雅总结

python - 解压嵌套字典的单列表理解

python - 使用列表理解创建列表列表

python - 将 Anaconda 安装从一个用户帐户移至另一个用户帐户

python - 将部分数据复制到另一列