执行文本预处理时Python出错

2024-10-01 15:45:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了几个函数来处理文本文档并将它们转换成单词包。在此之前,我通过删除停止词、标记化等来清理文本,并将清理后的文本文档存储为一个列表,我打算将其作为参数传递给另一个函数,该函数将从中创建单词包特性。在

功能如下:

def cleaningDocs(doc,stem):  # 'S' for Stemming, 'L' for Lemmatization
    """This function cleans each doc string by doing the following: 
    i)   Removing punctuation and other non alphabetical characters
    ii)  Convert to Lower case and split string into words (tokenization)
    ii)  Removes stop words (most frequent words)
    iii) Doing Stemming and Lemmatization
    """

    # Removing punctuations and other non alphabetic characters
    import re
    alphabets_only=re.sub(r'[^a-zA-Z]'," ",doc)

    # Converting to lower case and splitting the words(tokenization)
    words_lower=alphabets_only.lower().split()

    # Removing stop words (Words like 'a', 'an', 'is','the' which doesn't contribute anything
    from nltk.corpus import stopwords
    useful_words = [w for w in words_lower if not w in set(stopwords.words("english"))] 

    # Doing Stemming or Lemmatization (Normalising the text)
    from nltk.stem import PorterStemmer, WordNetLemmatizer
    if (stem=='S'):  # Choosing between Stemming ('S') and Lemmatization ('L')
        stemmer=PorterStemmer()
        final_words=[stemmer.stem(x) for x in useful_words]
    else: 
        lemma=WordNetLemmatizer()
        final_words=[lemma.lemmatize(x) for x in useful_words]

    return(str(" ".join(final_words)))    

下面是一个文档字符串列表,这是一个pandas系列对象。在

^{pr2}$

此文档中的每个元素都是一个字符串。基本上每个元素都是一个文本文档,我想对每个文本文档进行预处理(去掉停止词、词法化等),并将其保存为一个新的已处理列表。在

type(docs[0])
Out[55]:
str

理想情况下,我想做这样的事情:

doc=[]
for x in docs:
    doc.append(cleaningDocs(x,"L"))

因此,对于docs系列中的每个字符串文档,我们都用停止词和其他东西将其删除,并将其保存回文档列表中。在

上面的代码给了我这个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-56-61345bb4d581> in <module>()
      1 doc=[]
      2 for x in docs:
----> 3     doc.append(cleaningDocs(x,"L"))
      4 

<ipython-input-42-6e1c58274c3d> in cleaningDocs(doc, stem)
     13     # Removing punctuations and other non alphabetic characters
     14     import re
---> 15     alphabets_only=re.sub(r'[^a-zA-Z]'," ",doc)
     16 
     17     # Converting to lower case and splitting the words(tokenization)

/Users/mtripathi/anaconda/lib/python2.7/re.pyc in sub(pattern, repl, string, count, flags)
    153     a callable, it's passed the match object and must return
    154     a replacement string to be used."""
--> 155     return _compile(pattern, flags).sub(repl, string, count)
    156 
    157 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or buffer

然而,如果我通过在上面的for循环中添加break来传递docs的第一个元素(第一个文档),就可以对它进行除错了。在

doc=[]
for x in docs:
    doc.append(cleaningDocs(x,"L"))
    break

doc

如果您看到函数按要求执行,方法是从原始文档中删除停止字并将其词形化,然后将其保存回新的已处理文档列表中。但如果我一次只发送一个文件,这是有效的。在for循环中发送所有文档时,它会抛出一个错误,为什么会这样?。在

编辑:

好的,我刚刚检查了文档中每个元素的类型,发现有一些元素被铸造成float。见下文:

for x in docs: 
    print(type(x))
<type 'str'>
<type 'str'>
<type 'str'>
<type 'float'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>

所以有几件事:

1)我想看看这个文档中浮动的元素。 2) 一。第二,如果我想把所有的元素都转换成字符串,我想我们可以做.astype()?在


Tags: andthein文档元素docs列表for
1条回答
网友
1楼 · 发布于 2024-10-01 15:45:09

这里有两个主要思想:Boolean indexing和{a2}

布尔索引允许您使用真/假数组选择序列的子集,函数应用程序将单个函数应用于序列中的每个项。在

首先,应用isinstance来确定哪些元素是浮动的,然后对序列进行切片以获取元素。在

那么只要应用str就可以了。在

import pandas as pd

test = pd.Series(["Hey", "I'm", 1.0, "or", 2.0, "floats"])
# Find floats 
floats = test[test.apply(lambda x: isinstance(x, float))]
# Make all strings
test_as_strings = test.apply(str)

相关问题 更多 >

    热门问题