我正在编写一个从文件中删除重复单词的 python 程序。单词被定义为任何不带空格的字符序列,无论大小写如何,重复都是重复的,因此:duplicate、Duplicate、DUPLICATE、dUplIcaTe 都是重复的。它的工作方式是我读入原始文件并将其存储为字符串列表。然后我创建一个新的空列表并一次填充一个,检查当前字符串是否已存在于新列表中。当我尝试实现大小写转换时遇到问题,它会检查特定大小写格式的所有实例。我尝试将 if 语句重写为:
if elem and capital and title and lower not in uniqueList:
uniqueList.append(elem)
我也试过用 or 语句来写它:
if elem or capital or title or lower not in uniqueList:
uniqueList.append(elem)
但是,我仍然得到重复。程序正常工作的唯一方法是如果我这样编写代码:
def remove_duplicates(self):
"""
self.words is a class variable, which stores the original text as a list of strings
"""
uniqueList = []
for elem in self.words:
capital = elem.upper()
lower = elem.lower()
title = elem.title()
if elem == '\n':
uniqueList.append(elem)
else:
if elem not in uniqueList:
if capital not in uniqueList:
if title not in uniqueList:
if lower not in uniqueList:
uniqueList.append(elem)
self.words = uniqueList
有什么方法可以更优雅地编写这些嵌套的 if 语句?
红颜莎娜
LEATH
相关分类