簡體   English   中英

從字符串列表中刪除那些只有空格或由少於 3 個字母數字字符組成的字符串

[英]Remove from a list of strings, those strings that have only empty spaces or that are made up of less than 3 alphanumeric characters

import re

sentences_list = ['Hay 5 objetos rojos sobre la mesada de ahí.', 'Debajo de la mesada hay 4 objetos', '', '     ', "\taa!", '\t\n \n', '\n ', 'ai\n ', 'Salto rapidamente!!!', 'y la vio volar', '!', '   aa', 'aa', 'día']

#The problem with this is that there are several cases that need to be eliminated 
# and the complexity to figure that out should be resolved with a regex.
sentences_list = [i for a,i in enumerate(sentences_list) if i != ' ']

print(repr(sentences_list)) #print the already filtered list to verify

我得到了帶有句子分隔符的這些字符串,問題是有些句子不是真正的句子,或者不是真正的語言上重要的單位。

  • 那些少於 3 個字母數字字符(即 2 個字符或更少)的字符串必須從列表中刪除。

  • 那些為空的字符串""" " ,或者由單個符號"...!"組成的字符串 , ";" , ".\n" , "\taa!" 必須從名單中刪除。

  • 那些只有轉義字符而沒有其他字符(符號除外)或少於 3 個字母數字字符的字符串,例如"\t\n ab." , "\n." , "\n"必須從列表中刪除。

這是過濾掉不符合條件的子串元素后正確列表的樣子

['Hay 5 objetos rojos sobre la mesada de ahí.', 'Debajo de la mesada hay 4 objetos', 'Salto rapidamente!!!', 'y la vio volar', 'día']

您可以通過對每個字符調用.isalnum()並對這些值求和來計算字符串中字母數字字符的數量。 然后你可以只保留至少有 3 個具有列表理解的字符串。

sentences_list = [s for s in sentences_list if sum(c.isalnum() for c in s) >= 3]

你可以使用這個if子句:

if len(re.sub(r"\W", "", i)) >= 3

這是一個簡單的解決方案,可以過濾掉您需要的內容:

from string import punctuation

for sentence in sentences_list:
    trimmed_sentence = sentence.strip().strip(punctuation)
    if len (trimmed_sentence) > 2:
        print (sentence)

基本上它遍歷列表中的所有句子,修剪句子(空格,換行),修剪標點符號,然后檢查句子的長度是否大於 2。

還可以在此處了解更多有關 strip() 的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM