簡體   English   中英

如何使用python從列表中刪除空引號?

[英]how to remove the empty quotes from the list using python?

我有一個 python 腳本,可以在進行文本分析之前對文本進行預處理。 一些清理文本的功能是:

  • 刪除少於兩個字符的字符串。
  • 標記文本

問題是第一個函數返回一個列表,第二個函數獲取返回的列表並返回一個列表,因此它成為列表內的列表。 像這樣:

['[', "'الموضوع", "'", ',', "'إجتماع", "'", ',', "'بين", "'", ',',
"'الجنة", "'", ',', "'البحرية", "'", ',', "'الفرعية", "'", ',',]']

結果必須是這樣的:

['الموضوع', 'إجتماع', 'بين', 'الجنة', 'البحرية', 'الفرعية',]

移除停用詞的返回結果:

['ا', 'ل', 'م', 'و', 'ض', 'و', 'ع', ' ', 'إ', 'ج', 'ت', 'م', 'ا', 'ع', ' ', 'ب', 'ي', 'ن', ' ', 'ا', 'ل', 'ج', 'ن', 'ة', ' ', 'ا', 'ل', 'ب', 'ح', 'ر', 'ي', 'ة', ' ', 'ا', 'ل', 'ف', 'ر', 'ع', 'ي', 'ة', ' ', 'و', 'ن', 'ظ', 'ي', 'ر', 'ت', 'ه', 'ا', ' ', 'ف', 'ي', ' ', 'م', 'ب', 'س', 'و', 'ط', ' ', 'ا', 'ل', 'م', 'س', 'ت', 'ن', 'د', ' ', 'ب', 'ر', 'ق', 'ي', 'ة', ' ', 'ر', 'ق', 'م', ' ', '1', '7', '1', 'ع', ' ', 'ت', 'ا', 'ر', 'ي', 'خ', ' ', '1', '2', '1', ]

結果必須是:

['تاريخ', '1212019','الموضوع', 'إجتماع', 'بين', 'الجنة', 'البحرية', 'الفرعية',]

代碼

def remove_1char(text):
    tokens = text.split()
    tokens = [word for word in tokens if len(word) > 1]   
    result = str(tokens)
    write_file("remove_1char.txt",result)
    return result

def tokenize_text(text):
    tokens=word_tokenize(text)
    write_file("tokenize_text.txt",tokens)
    return tokens



 def remove_stopwords(tokens):
       write_file("tokens_before_remove.txt",tokens)
       stop_word_list = set(stopwords.words('arabic'))
       clean_tokens= [tok for tok in tokens if tok not in stop_word_list]
       write_file("remove_stop_word.txt",clean_tokens)
       return clean_tokens

def clean_text(text):
    rmws = remove_whiteSpace(text)
    rmp = remove_punctuations(rmws)
    rmd = remove_diacritics(rmp)
    rmrc = remove_repeating_char(rmd)
    rm1c = remove_1char(rmrc)
    clean_tokens = remove_stopwords(rm1c)
    write_file("result.txt",clean_tokens)
    return clean_tokens

那么如何解決這個問題呢?

讓我們打開一個 Python REPL 並檢查您的代碼。

我假設第一行指定了輸入字符串,將其分配給一個變量。

>>> l = ['الموضوع', 'إجتماع', 'بين', 'الجنة', 'البحرية', 'الفرعية',]
>>> l
['الموضوع', 'إجتماع', 'بين', 'الجنة', 'البحرية', 'الفرعية']

您沒有指定調用哪個函數,但我假設您首先為每個輸入字符串調用函數remove_1char 我們將依次調用函數的行以查看列表中第一項的結果,我們將其稱為text

>>> text = l[0]
>>> tokens = text.split()
>>> tokens
>>> ['الموضوع']

由於輸入序列中的每個詞都由一個詞組成,因此輸出符合預期。

>>> tokens = [word for word in tokens if len(word) > 1]
>>> tokens
['الموضوع']

並且所有單詞都有超過 1 個字符。 也符合預期。

>>> result = str(tokens)
>>> result
"['الموضوع']"
>>>

在這一行中,列表的字符串表示被分配給結果。 這可能不是你想要的。 我認為您想將令牌連接到單個字符串。 這可以通過join函數來完成。

>>> result = ' '.join(tokens)
>>> result
'الموضوع'
>>>

暫無
暫無

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

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