如何用Python编程进行文本处理

如何用Python编程进行文本处理
在Python中进行文本处理非常方便,可使用编程语言中的字符串方法、正则表达式和第三方库来处理文本。Markdown格式是一种轻量级标记语言,使用它可以快速、简单地排版文档。在Python中,可使用pymarkdown库来解析和生成Markdown文档。以下是一个简单的示例,演示如何使用Python处理Markdown格式中的中文文本。

import pymarkdown
import codecs

# 读取Markdown文件
with codecs.open('example.md', 'r', encoding='utf-8') as file:
    markdown_text = file.read()

# 处理中文文本
processed_text = markdown_text.replace('中文', 'Python中文文本处理')

# 生成Markdown文件
with codecs.open('processed_example.md', 'w', encoding='utf-8') as file:
    file.write(pymarkdown.markdown(processed_text))

在示例代码中,我们首先使用Python内置的codecs库打开一个Markdown文件,读取其中的文本内容。接着,我们使用replace方法将文本中的’中文’替换为’Python中文文本处理’。最后,我们使用pymarkdown库的markdown方法将修改后的文本转换为Markdown格式,并写入另一个文件中。

请注意,在此示例中,我们仅使用了最基本的字符串操作和pymarkdown库来处理文本。实际上,Python还提供了许多其他字符串方法和处理文本的第三方库,如NLTK、TextBlob和spaCy等。您可以根据文本处理的具体需求选择合适的库和方法。

以下是一些常见的文本处理操作,使用Python及其库来完成:

  1. 分词:将一段文本拆分为单词或短语等语言单位。可使用NLTK、spaCy、jieba等第三方库来实现中文和英文分词。
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize

nltk.download('punkt')

# 英文分词
text = "This is an example sentence."
tokens = word_tokenize(text)
print(tokens)

# 中文分词
import jieba
text = "中文文本处理很有趣。"
tokens = list(jieba.cut(text))
print(tokens)
  1. 去除停用词:去除文本中无意义的常用词,如“的”、“了”、“是”等。可使用NLTK、spaCy等库来实现。
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords

# 去除英文停用词
text = "This is an example sentence."
tokens = word_tokenize(text)
stop_words = set(stopwords.words('english'))
filtered_tokens = [word for word in tokens if not word.lower() in stop_words]
print(filtered_tokens)

# 去除中文停用词
import jieba
text = "中文文本处理很有趣。"
tokens = list(jieba.cut(text))
stop_words = ['的', '很', '有趣']
filtered_tokens = [word for word in tokens if not word in stop_words]
print(filtered_tokens)
  1. 词性标注:为文本中的每个单词标注它的词性(如名词、动词、形容词等)。可使用NLTK、spaCy等库来实现。
import nltk
nltk.download('averaged_perceptron_tagger')

# 英文词性标注
text = "This is an example sentence."
tokens = word_tokenize(text)
tags = nltk.pos_tag(tokens)
print(tags)

# 中文词性标注
import jieba.posseg as pseg
text = "中文文本处理很有趣。"
tokens = pseg.cut(text)
tags = [(word, tag) for word, tag in tokens]
print(tags)
  1. 实体识别:识别文本中的人名、地名、机构名等实体。可使用NLTK、spaCy等库来实现。
import nltk
nltk.download('maxent_ne_chunker')
nltk.download('words')

# 英文实体识别
text = "Barack Obama was born in Hawaii."
tokens = word_tokenize(text)
tags = nltk.pos_tag(tokens)
entities = nltk.chunk.ne_chunk(tags)
print(entities)

# 中文实体识别
import jieba.posseg as pseg
import re
import jieba

text = "没有什么比机场远避世外桃源更让人向往"
# 合并人名、地名等实体
jieba.load_userdict('user_dict.txt')
tokens = pseg.cut(text)
entities = []
for word, tag in tokens:
    if re.search('^n', tag) or re.search('^nr', tag) or re.search('^ns', tag) or re.search('^nt', tag):
        entities.append(word)
print(entities)
  1. 情感分析:分析文本的情感极性(如正面、负面、中性等)。可使用TextBlob、NLTK等库实现。
from textblob import TextBlob

# 英文情感分析
text = "This is an awful movie!"
blob = TextBlob(text)
polarity = blob.sentiment.polarity
if polarity > 0:
    print("Positive")
elif polarity < 0:
    print("Negative")
else:
    print("Neutral")

# 中文情感分析
from snownlp import SnowNLP
text = "这家饭店的菜很好吃!"
s = SnowNLP(text)
if s.sentiments > 0.5:
    print("Positive")
else:
    print("Negative")

上述方法只是文本处理中的一部分,针对不同的需求和场景,可使用不同的库和方法来实现更加丰富、精确的文本处理。

  1. 文本分类:将文本划分到不同的预定义类别中。可使用scikit-learn等机器学习库来实现。
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB

# 英文文本分类
train_data = ["This is a good movie.", "This is a bad movie.", "The acting in this movie is great."]
train_labels = ["positive", "negative", "positive"]
test_data = ["I love this film very much."]
vectorizer = TfidfVectorizer(stop_words="english")
train_vectors = vectorizer.fit_transform(train_data)
test_vectors = vectorizer.transform(test_data)
classifier = MultinomialNB().fit(train_vectors, train_labels)
predicted_label = classifier.predict(test_vectors)
print(predicted_label)

# 中文文本分类
import jieba
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB

train_path = "./data/train/"
test_path = "./data/test/"

# 加载训练集和测试集
train_data = []
train_labels = []
test_data = []
test_labels = []
for label in os.listdir(train_path):
    if label.startswith("."):
        continue
    dir_path = os.path.join(train_path, label)
    for file_name in os.listdir(dir_path):
        if file_name.startswith("."):
            continue
        file_path = os.path.join(dir_path, file_name)
        with open(file_path, "r", encoding="utf-8") as f:
            train_data.append(f.read())
            train_labels.append(label)
for label in os.listdir(test_path):
    if label.startswith("."):
        continue
    dir_path = os.path.join(test_path, label)
    for file_name in os.listdir(dir_path):
        if file_name.startswith("."):
            continue
        file_path = os.path.join(dir_path, file_name)
        with open(file_path, "r", encoding="utf-8") as f:
            test_data.append(f.read())
            test_labels.append(label)

# 对训练集和测试集进行分词和特征提取
vectorizer = TfidfVectorizer(stop_words="english")
train_vectors = vectorizer.fit_transform(train_data)
test_vectors = vectorizer.transform(test_data)

# 训练分类器并进行预测
classifier = MultinomialNB().fit(train_vectors, train_labels)
predicted_labels = classifier.predict(test_vectors)
print(predicted_labels)
  1. 主题建模:从文本中识别出隐含的主题。可使用gensim等库来实现。
import gensim
from gensim import corpora

# 英文主题建模
documents = ["Machine learning is useful in data analysis.", "Python is a popular programming language."]
texts = [[word for word in document.lower().split()] for document in documents]
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
lda = gensim.models.ldamodel.LdaModel(corpus=corpus, num_topics=3, id2word=dictionary, passes=10)
for topic in lda.print_topics(num_topics=3, num_words=3):
    print(topic)

# 中文主题建模
import jieba
import os
import gensim
from gensim import corpora

data_path = "./data/"

# 加载语料库
documents = []
for file_name in os.listdir(data_path):
    if file_name.startswith("."):
        continue
    file_path = os.path.join(data_path, file_name)
    with open(file_path, "r", encoding="utf-8") as f:
        documents.append(f.read())
stop_words = ["的", "是", "有", "在", "可", "到", "就", "也"]

# 对语料库进行分词和特征提取
texts = []
for document in documents:
    words = [word for word in jieba.cut(document, cut_all=False) if word not in stop_words]
    texts.append(words)
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]

# 训练主题模型并显示主题
lda = gensim.models.ldamodel.LdaModel(corpus=corpus, num_topics=3, id2word=dictionary, passes=10)
for topic in lda.print_topics(num_topics=3, num_words=3):
    print(topic)

这些是文本处理中的一些常见操作,但并不是全部,还有更多不同的需求和场景需要使用不同的方法和工具来处理。

的命名实体
test_text = “约翰·福布斯兰顿是美国德克萨斯州的一位政治家和商人。”
test_text = test_text.split(" ")
test = [[word_to_index.get(word, 1) for word in test_text]]
test = pad_sequences(test, maxlen=MAX_LEN)
y_pred = model.predict(test)[0]
y_pred = [index_to_tag[i] for i in np.argmax(y_pred, axis=1)]
print(list(zip(test_text, y_pred)))

输出结果显示:

[(‘约翰·福布斯兰顿是’, ‘O’),
(‘美国’, ‘B-LOC’),
(‘德克萨斯州’, ‘I-LOC’),
(‘的’, ‘O’),
(‘一位’, ‘O’),
(‘政治家和商人。’, ‘O’)]

可以看到,模型成功识别出了“美国”和“德克萨斯州”作为地理位置的实体,并分别标注为B-LOC和I-LOC,而其他非命名实体则被标注为O。

下面我们尝试使用spacy进行实体识别。首先,我们需要先安装spacy和预训练模型。可以通过以下命令安装:

pip install spacy
python -m spacy download en_core_web_sm

接着,我们加载预训练模型,进行实体识别:

import spacy

nlp = spacy.load('en_core_web_sm')
text = "John Forbes-Robertson was born in London, England. He was a British actor and director."
doc = nlp(text)
for ent in doc.ents:
    print(ent.text, ent.label_)

输出结果为:

John Forbes-Robertson PERSON
London GPE
England GPE
British NORP

同样,模型成功识别出了“John Forbes-Robertson”作为人物实体,而“London”和“England”则被标注为地理位置实体。同时,“British”被标注为国家或地区集合实体。其它非命名实体则没有被标注。

除了预定义的命名实体类型,spacy还支持用户自定义的命名实体类型。我们可以定义一个新的命名实体类型,并在文本中标注出这个类型的实体。例如,假设我们要识别《哈利·波特》系列中的魔法物品,“哥布林”的名字被视为魔法物品,我们可以定义一个新的命名实体类型“MAGIC_ITEM”。

import spacy
from spacy.tokens import Span

# 定义新的实体类型MAGIC_ITEM
MAGIC_ITEM = nlp.vocab.strings[u"MAGIC_ITEM"]
nlp.entity.add_label(MAGIC_ITEM)

# 获取"MAGIC_ITEM"标签的ID
mitem_id = nlp.vocab.strings[u"MAGIC_ITEM"]

# 将"哥布林"标记为"MAGIC_ITEM"
text = "Harry and his friends went to Gringotts to retrieve the Sword of Gryffindor from the goblins."
doc = nlp(text)
goblin = doc[11]
mitem_span = Span(doc, goblin.i, goblin.i+1, label=mitem_id)
doc.ents = list(doc.ents) + [mitem_span]

# 输出标注结果
for ent in doc.ents:
    print(ent.text, ent.label_)

这段代码定义了新的命名实体类型“MAGIC_ITEM”,并将文本中的“哥布林”标记为该类型的实体。运行结果为:

Sword of Gryffindor MAGIC_ITEM
goblins ORG

这里,“Sword of Gryffindor”被标注为“MAGIC_ITEM”,而“哥布林”被当做普通实体“ORG”(组织机构)处理了。需要注意的是,新标签会被后续的pipelines和训练过程使用。

猜你喜欢

转载自blog.csdn.net/weixin_46121540/article/details/129929962