Python 去掉单词中的标点符号

Python 去掉单词中的标点符号,python,Python,我有一个函数,它以标点符号和单词列表作为参数。该函数查找每个单词并拆分标点符号。例如: ["I...love", "you"] ---> ["I","love","you"] 唯一的问题是,我使用了一种所谓的“不可理解的列表理解”来做这件事,它表现出一些奇怪的行为: def take_out(symbol, word_list): for word in word_list: if symbol in word and "http" not in

我有一个函数,它以标点符号和单词列表作为参数。该函数查找每个单词并拆分标点符号。例如:

["I...love", "you"] ---> ["I","love","you"]
唯一的问题是,我使用了一种所谓的“不可理解的列表理解”来做这件事,它表现出一些奇怪的行为:

def take_out(symbol, word_list):
        for word in word_list:
            if symbol in word and "http" not in word :
                word_list[word_list.index(word)] = (" ".join([x for x in word.split(symbol)])).split()
        word_list = [[item] if isinstance(item, str) else item for item in word_list]
        word_list = [item for sublist in word_list for item in sublist]
        return word_list

有没有人能提出另一种方法来完成这项任务,而不必像我一样使用模糊的方法。

如果我正确理解了你的问题,请尝试以下方法:

z = []
for i in ["I...love","you"]:
    for j in i.split("..."):
        z.append(j)
print(z)

希望这有帮助

您可以通过插入几行打印行来查看代码的功能。它将帮助你理解它

以下是输出:

代码首先拆分列表中的每个元素,并将结果替换为原始结果。因此,对于列表:['I…love','you','…或者not?],它会得到它的第一个成员'I…love',将其拆分,结果是一个单词列表['I','love']。将结果放置在原始[['I'、'love']、'you'、'…或否?]的位置。继续第二个元素。没有要拆分的内容,因此它将移动到第三个并拆分它。退出循环

单词列表现在看起来像[['I'、'love']、'you'、['or'、'not?]]。第一个列表理解用于规范化列表中的所有元素。你现在明白了吗?。item if已经是列表或[item]if是字符串。因此,“你”变成了[“你”


上一个列表理解需要上一个规范化才能工作。它所做的是从内部列表中取出每个项目,并将它们放入一个列表中。所以['I'、'love']、['you']、['or'、'not?]]变成了['I'、'love'、'you'、'or'、'not?]。我希望这有助于您更好地理解代码。

为什么不编写一些您确实理解的代码呢?如果您不理解列表理解,请使用循环和条件将其写出,并在那里进行调试。如果你以后想把它作为列表理解放在一起,那么你可以一直担心语法。@jornsharpe我确实理解我写的东西,但我不喜欢它的复杂性。我发布这个问题是为了看看是否有更简单的方法。尝试将函数拆分为更小的函数,每个函数都有更小的任务要执行,例如,
http
check,
isinstance()
check——这是其他函数的任务。限制
take_out()
仅限于一项任务:将带有给定标点符号的项目拆分为几个单词并替换它们:
def take_out(符号,单词):返回[nou punch_word for w in words for nou punch_word in w.split(符号)]
那么“奇怪行为”是什么意思呢?如果它可以工作,但你认为它可以改进,试试。谢谢DJK,我的编辑它工作得很好。我所寻求的是一种更简单的方法来完成这项任务,这似乎可以达到目的。
def take_out(symbol, word_list):
  for word in word_list:
    if symbol in word and "http" not in word :
      word_list[word_list.index(word)] = (" ".join([x for x in word.split(symbol)])).split()
      print(word_list)
  word_list = [[item] if isinstance(item, str) else item for item in word_list]
  print(word_list)
  word_list = [item for sublist in word_list for item in sublist]
  print(word_list)
  return word_list
>>> take_out('.', ['I...love','you','...or not?'],)
  [['I', 'love'], 'you', '...or not?']
  [['I', 'love'], 'you', ['or', 'not?']]
  [['I', 'love'], ['you'], ['or', 'not?']]
  ['I', 'love', 'you', 'or', 'not?']