25个Python文本处理案例

  • 提取 PDF 内容
  • 提取 Word 内容
  • 提取 Web 网页内容
  • 读取 Json 数据
  • 读取 CSV 数据
  • 删除字符串中的标点符号
  • 使用 NLTK 删除停用词
  • 使用 TextBlob 更正拼写
  • 使用 NLTK 和 TextBlob 的词标记化
  • 使用 NLTK 提取句子单词或短语的词干列表
  • 使用 NLTK 进行句子或短语词形还原
  • 使用 NLTK 从文本文件中查找每个单词的频率
  • 从语料库中创建词云
  • NLTK 词法散布图
  • 使用 countvectorizer 将文本转换为数字
  • 使用 TF-IDF 创建文档术语矩阵
  • 为给定句子生成 N-gram
  • 使用带有二元组的 sklearn CountVectorize 词汇规范
  • 使用 TextBlob 提取名词短语
  • 如何计算词-词共现矩阵
  • 使用 TextBlob 进行情感分析
  • 使用 Goslate 进行语言翻译
  • 使用 TextBlob 进行语言检测和翻译
  • 使用 TextBlob 获取定义和同义词
  • 使用 TextBlob 获取反义词列表

    提取 PDF 内容

    ```python

    pip install PyPDF2 安装 PyPDF2

    import PyPDF2 from PyPDF2 import PdfFileReader

Creating a pdf file object.

pdf = open(“test.pdf”, “rb”)

Creating pdf reader object.

pdf_reader = PyPDF2.PdfFileReader(pdf)

Checking total number of pages in a pdf file.

print(“Total number of Pages:”, pdf_reader.numPages)

Creating a page object.

page = pdf_reader.getPage(200)

Extract data from a specific page number.

print(page.extractText())

Closing the object.

pdf.close()

  1. <a name="fhevd"></a>
  2. ## 提取 Word 内容
  3. ```python
  4. # pip install python-docx 安装 python-docx
  5. import docx
  6. def main():
  7. try:
  8. doc = docx.Document('test.docx') # Creating word reader object.
  9. data = ""
  10. fullText = []
  11. for para in doc.paragraphs:
  12. fullText.append(para.text)
  13. data = '\n'.join(fullText)
  14. print(data)
  15. except IOError:
  16. print('There was an error opening the file!')
  17. return
  18. if __name__ == '__main__':
  19. main()

提取 Web 网页内容

  1. # pip install bs4 安装 bs4
  2. from urllib.request import Request, urlopen
  3. from bs4 import BeautifulSoup
  4. req = Request('http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1',
  5. headers={'User-Agent': 'Mozilla/5.0'})
  6. webpage = urlopen(req).read()
  7. # Parsing
  8. soup = BeautifulSoup(webpage, 'html.parser')
  9. # Formating the parsed html file
  10. strhtm = soup.prettify()
  11. # Print first 500 lines
  12. print(strhtm[:500])
  13. # Extract meta tag value
  14. print(soup.title.string)
  15. print(soup.find('meta', attrs={'property':'og:description'}))
  16. # Extract anchor tag value
  17. for x in soup.find_all('a'):
  18. print(x.string)
  19. # Extract Paragraph tag value
  20. for x in soup.find_all('p'):
  21. print(x.text)

读取 Json 数据

  1. import requests
  2. import json
  3. r = requests.get("https://support.oneskyapp.com/hc/en-us/article_attachments/202761727/example_2.json")
  4. res = r.json()
  5. # Extract specific node content.
  6. print(res['quiz']['sport'])
  7. # Dump data as string
  8. data = json.dumps(res)
  9. print(data)

读取 CSV 数据

  1. import csv
  2. with open('test.csv','r') as csv_file:
  3. reader =csv.reader(csv_file)
  4. next(reader) # Skip first row
  5. for row in reader:
  6. print(row)

删除字符串中的标点符号

  1. import re
  2. import string
  3. data = "Stuning even for the non-gamer: This sound track was beautiful!\
  4. It paints the senery in your mind so well I would recomend\
  5. it even to people who hate vid. game music! I have played the game Chrono \
  6. Cross but out of all of the games I have ever played it has the best music! \
  7. It backs away from crude keyboarding and takes a fresher step with grate\
  8. guitars and soulful orchestras.\
  9. It would impress anyone who cares to listen!"
  10. # Methood 1 : Regex
  11. # Remove the special charaters from the read string.
  12. no_specials_string = re.sub('[!#?,.:";]', '', data)
  13. print(no_specials_string)
  14. # Methood 2 : translate()
  15. # Rake translator object
  16. translator = str.maketrans('', '', string.punctuation)
  17. data = data.translate(translator)
  18. print(data)

使用 NLTK 删除停用词

  1. from nltk.corpus import stopwords
  2. data = ['Stuning even for the non-gamer: This sound track was beautiful!\
  3. It paints the senery in your mind so well I would recomend\
  4. it even to people who hate vid. game music! I have played the game Chrono \
  5. Cross but out of all of the games I have ever played it has the best music! \
  6. It backs away from crude keyboarding and takes a fresher step with grate\
  7. guitars and soulful orchestras.\
  8. It would impress anyone who cares to listen!']
  9. # Remove stop words
  10. stopwords = set(stopwords.words('english'))
  11. output = []
  12. for sentence in data:
  13. temp_list = []
  14. for word in sentence.split():
  15. if word.lower() not in stopwords:
  16. temp_list.append(word)
  17. output.append(' '.join(temp_list))
  18. print(output)

使用 TextBlob 更正拼写

  1. from textblob import TextBlob
  2. data = "Natural language is a cantral part of our day to day life, and it's so antresting to work on any problem related to langages."
  3. output = TextBlob(data).correct()
  4. print(output)

使用 NLTK 和 TextBlob 的词标记化

  1. import nltk
  2. from textblob import TextBlob
  3. data = "Natural language is a central part of our day to day life, and it's so interesting to work on any problem related to languages."
  4. nltk_output = nltk.word_tokenize(data)
  5. textblob_output = TextBlob(data).words
  6. print(nltk_output)
  7. print(textblob_output)

OutPut

  1. ['Natural', 'language', 'is', 'a', 'central', 'part', 'of', 'our', 'day', 'to', 'day', 'life', ',', 'and', 'it', "'s", 'so', 'interesting', 'to', 'work', 'on', 'any', 'problem', 'related', 'to', 'languages', '.']
  2. ['Natural', 'language', 'is', 'a', 'central', 'part', 'of', 'our', 'day', 'to', 'day', 'life', 'and', 'it', "'s", 'so', 'interesting', 'to', 'work', 'on', 'any', 'problem', 'related', 'to', 'languages']

使用 NLTK 提取句子单词或短语的词干列表

  1. from nltk.stem import PorterStemmer
  2. st = PorterStemmer()
  3. text = ['Where did he learn to dance like that?',
  4. 'His eyes were dancing with humor.',
  5. 'She shook her head and danced away',
  6. 'Alex was an excellent dancer.']
  7. output = []
  8. for sentence in text:
  9. output.append(" ".join([st.stem(i) for i in sentence.split()]))
  10. for item in output:
  11. print(item)
  12. print("-" * 50)
  13. print(st.stem('jumping'), st.stem('jumps'), st.stem('jumped'))

OutPut

  1. where did he learn to danc like that?
  2. hi eye were danc with humor.
  3. she shook her head and danc away
  4. alex wa an excel dancer.
  5. --------------------------------------------------
  6. jump jump jump

使用 NLTK 进行句子或短语词形还原

  1. from nltk.stem import WordNetLemmatizer
  2. wnl = WordNetLemmatizer()
  3. text = ['She gripped the armrest as he passed two cars at a time.',
  4. 'Her car was in full view.',
  5. 'A number of cars carried out of state license plates.']
  6. output = []
  7. for sentence in text:
  8. output.append(" ".join([wnl.lemmatize(i) for i in sentence.split()]))
  9. for item in output:
  10. print(item)
  11. print("*" * 10)
  12. print(wnl.lemmatize('jumps', 'n'))
  13. print(wnl.lemmatize('jumping', 'v'))
  14. print(wnl.lemmatize('jumped', 'v'))
  15. print("*" * 10)
  16. print(wnl.lemmatize('saddest', 'a'))
  17. print(wnl.lemmatize('happiest', 'a'))
  18. print(wnl.lemmatize('easiest', 'a'))

OutPut

  1. She gripped the armrest a he passed two car at a time.
  2. Her car wa in full view.
  3. A number of car carried out of state license plates.
  4. **********
  5. jump
  6. jump
  7. jump
  8. **********
  9. sad
  10. happy
  11. easy

使用 NLTK 从文本文件中查找每个单词的频率

  1. import nltk
  2. from nltk.corpus import webtext
  3. from nltk.probability import FreqDist
  4. nltk.download('webtext')
  5. wt_words = webtext.words('testing.txt')
  6. data_analysis = nltk.FreqDist(wt_words)
  7. # Let's take the specific words only if their frequency is greater than 3.
  8. filter_words = dict([(m, n) for m, n in data_analysis.items() if len(m) > 3])
  9. for key in sorted(filter_words):
  10. print("%s: %s" % (key, filter_words[key]))
  11. data_analysis = nltk.FreqDist(filter_words)
  12. data_analysis.plot(25, cumulative=False)

OutPut

  1. [nltk_data] Downloading package webtext to
  2. [nltk_data] C:\Users\amit\AppData\Roaming\nltk_data...
  3. [nltk_data] Unzipping corpora\webtext.zip.
  4. 1989: 1
  5. Accessing: 1
  6. Analysis: 1
  7. Anyone: 1
  8. Chapter: 1
  9. Coding: 1
  10. Data: 1
  11. ...

从语料库中创建词云

  1. import nltk
  2. from nltk.corpus import webtext
  3. from nltk.probability import FreqDist
  4. from wordcloud import WordCloud
  5. import matplotlib.pyplot as plt
  6. nltk.download('webtext')
  7. wt_words = webtext.words('testing.txt') # Sample data
  8. data_analysis = nltk.FreqDist(wt_words)
  9. filter_words = dict([(m, n) for m, n in data_analysis.items() if len(m) > 3])
  10. wcloud = WordCloud().generate_from_frequencies(filter_words)
  11. # Plotting the wordcloud
  12. plt.imshow(wcloud, interpolation="bilinear")
  13. plt.axis("off")
  14. (-0.5, 399.5, 199.5, -0.5)
  15. plt.show()

NLTK 词法散布图

  1. import nltk
  2. from nltk.corpus import webtext
  3. from nltk.probability import FreqDist
  4. from wordcloud import WordCloud
  5. import matplotlib.pyplot as plt
  6. words = ['data', 'science', 'dataset']
  7. nltk.download('webtext')
  8. wt_words = webtext.words('testing.txt') # Sample data
  9. points = [(x, y) for x in range(len(wt_words))
  10. for y in range(len(words)) if wt_words[x] == words[y]]
  11. if points:
  12. x, y = zip(*points)
  13. else:
  14. x = y = ()
  15. plt.plot(x, y, "rx", scalex=.1)
  16. plt.yticks(range(len(words)), words, color="b")
  17. plt.ylim(-1, len(words))
  18. plt.title("Lexical Dispersion Plot")
  19. plt.xlabel("Word Offset")
  20. plt.show()

使用 countvectorizer 将文本转换为数字

  1. import pandas as pd
  2. from sklearn.feature_extraction.text import CountVectorizer
  3. # Sample data for analysis
  4. data1 = "Java is a language for programming that develops a software for several platforms. A compiled code or bytecode on Java application can run on most of the operating systems including Linux, Mac operating system, and Linux. Most of the syntax of Java is derived from the C++ and C languages."
  5. data2 = "Python supports multiple programming paradigms and comes up with a large standard library, paradigms included are object-oriented, imperative, functional and procedural."
  6. data3 = "Go is typed statically compiled language. It was created by Robert Griesemer, Ken Thompson, and Rob Pike in 2009. This language offers garbage collection, concurrency of CSP-style, memory safety, and structural typing."
  7. df1 = pd.DataFrame({'Java': [data1], 'Python': [data2], 'Go': [data2]})
  8. # Initialize
  9. vectorizer = CountVectorizer()
  10. doc_vec = vectorizer.fit_transform(df1.iloc[0])
  11. # Create dataFrame
  12. df2 = pd.DataFrame(doc_vec.toarray().transpose(),
  13. index=vectorizer.get_feature_names())
  14. # Change column headers
  15. df2.columns = df1.columns
  16. print(df2)

OutPut

  1. Go Java Python
  2. and 2 2 2
  3. application 0 1 0
  4. are 1 0 1
  5. bytecode 0 1 0
  6. can 0 1 0
  7. code 0 1 0
  8. comes 1 0 1
  9. compiled 0 1 0
  10. derived 0 1 0
  11. develops 0 1 0
  12. for 0 2 0
  13. from 0 1 0
  14. functional 1 0 1
  15. imperative 1 0 1
  16. ...

使用 TF-IDF 创建文档术语矩阵

  1. import pandas as pd
  2. from sklearn.feature_extraction.text import TfidfVectorizer
  3. # Sample data for analysis
  4. data1 = "Java is a language for programming that develops a software for several platforms. A compiled code or bytecode on Java application can run on most of the operating systems including Linux, Mac operating system, and Linux. Most of the syntax of Java is derived from the C++ and C languages."
  5. data2 = "Python supports multiple programming paradigms and comes up with a large standard library, paradigms included are object-oriented, imperative, functional and procedural."
  6. data3 = "Go is typed statically compiled language. It was created by Robert Griesemer, Ken Thompson, and Rob Pike in 2009. This language offers garbage collection, concurrency of CSP-style, memory safety, and structural typing."
  7. df1 = pd.DataFrame({'Java': [data1], 'Python': [data2], 'Go': [data2]})
  8. # Initialize
  9. vectorizer = TfidfVectorizer()
  10. doc_vec = vectorizer.fit_transform(df1.iloc[0])
  11. # Create dataFrame
  12. df2 = pd.DataFrame(doc_vec.toarray().transpose(),
  13. index=vectorizer.get_feature_names())
  14. # Change column headers
  15. df2.columns = df1.columns
  16. print(df2)

OutPut

  1. Go Java Python
  2. and 0.323751 0.137553 0.323751
  3. application 0.000000 0.116449 0.000000
  4. are 0.208444 0.000000 0.208444
  5. bytecode 0.000000 0.116449 0.000000
  6. can 0.000000 0.116449 0.000000
  7. code 0.000000 0.116449 0.000000
  8. comes 0.208444 0.000000 0.208444
  9. compiled 0.000000 0.116449 0.000000
  10. derived 0.000000 0.116449 0.000000
  11. develops 0.000000 0.116449 0.000000
  12. for 0.000000 0.232898 0.000000
  13. ...

为给定句子生成 N-gram

NLTK

  1. import nltk
  2. from nltk.util import ngrams
  3. # Function to generate n-grams from sentences.
  4. def extract_ngrams(data, num):
  5. n_grams = ngrams(nltk.word_tokenize(data), num)
  6. return [ ' '.join(grams) for grams in n_grams]
  7. data = 'A class is a blueprint for the object.'
  8. print("1-gram: ", extract_ngrams(data, 1))
  9. print("2-gram: ", extract_ngrams(data, 2))
  10. print("3-gram: ", extract_ngrams(data, 3))
  11. print("4-gram: ", extract_ngrams(data, 4))

TextBlob

  1. from textblob import TextBlob
  2. # Function to generate n-grams from sentences.
  3. def extract_ngrams(data, num):
  4. n_grams = TextBlob(data).ngrams(num)
  5. return [ ' '.join(grams) for grams in n_grams]
  6. data = 'A class is a blueprint for the object.'
  7. print("1-gram: ", extract_ngrams(data, 1))
  8. print("2-gram: ", extract_ngrams(data, 2))
  9. print("3-gram: ", extract_ngrams(data, 3))
  10. print("4-gram: ", extract_ngrams(data, 4))

OutPut

  1. 1-gram: ['A', 'class', 'is', 'a', 'blueprint', 'for', 'the', 'object']
  2. 2-gram: ['A class', 'class is', 'is a', 'a blueprint', 'blueprint for', 'for the', 'the object']
  3. 3-gram: ['A class is', 'class is a', 'is a blueprint', 'a blueprint for', 'blueprint for the', 'for the object']
  4. 4-gram: ['A class is a', 'class is a blueprint', 'is a blueprint for', 'a blueprint for the', 'blueprint for the object']

使用带有二元组的 sklearn CountVectorize 词汇规范

  1. import pandas as pd
  2. from sklearn.feature_extraction.text import CountVectorizer
  3. # Sample data for analysis
  4. data1 = "Machine language is a low-level programming language. It is easily understood by computers but difficult to read by people. This is why people use higher level programming languages. Programs written in high-level languages are also either compiled and/or interpreted into machine language so that computers can execute them."
  5. data2 = "Assembly language is a representation of machine language. In other words, each assembly language instruction translates to a machine language instruction. Though assembly language statements are readable, the statements are still low-level. A disadvantage of assembly language is that it is not portable, because each platform comes with a particular Assembly Language"
  6. df1 = pd.DataFrame({'Machine': [data1], 'Assembly': [data2]})
  7. # Initialize
  8. vectorizer = CountVectorizer(ngram_range=(2, 2))
  9. doc_vec = vectorizer.fit_transform(df1.iloc[0])
  10. # Create dataFrame
  11. df2 = pd.DataFrame(doc_vec.toarray().transpose(),
  12. index=vectorizer.get_feature_names())
  13. # Change column headers
  14. df2.columns = df1.columns
  15. print(df2)

OutPut

  1. Assembly Machine
  2. also either 0 1
  3. and or 0 1
  4. are also 0 1
  5. are readable 1 0
  6. are still 1 0
  7. assembly language 5 0
  8. because each 1 0
  9. but difficult 0 1
  10. by computers 0 1
  11. by people 0 1
  12. can execute 0 1
  13. ...

使用 TextBlob 提取名词短语

  1. from textblob import TextBlob
  2. #Extract noun
  3. blob = TextBlob("Canada is a country in the northern part of North America.")
  4. for nouns in blob.noun_phrases:
  5. print(nouns)

OutPut

  1. canada
  2. northern part
  3. america

如何计算词-词共现矩阵

  1. import numpy as np
  2. import nltk
  3. from nltk import bigrams
  4. import itertools
  5. import pandas as pd
  6. def generate_co_occurrence_matrix(corpus):
  7. vocab = set(corpus)
  8. vocab = list(vocab)
  9. vocab_index = {word: i for i, word in enumerate(vocab)}
  10. # Create bigrams from all words in corpus
  11. bi_grams = list(bigrams(corpus))
  12. # Frequency distribution of bigrams ((word1, word2), num_occurrences)
  13. bigram_freq = nltk.FreqDist(bi_grams).most_common(len(bi_grams))
  14. # Initialise co-occurrence matrix
  15. # co_occurrence_matrix[current][previous]
  16. co_occurrence_matrix = np.zeros((len(vocab), len(vocab)))
  17. # Loop through the bigrams taking the current and previous word,
  18. # and the number of occurrences of the bigram.
  19. for bigram in bigram_freq:
  20. current = bigram[0][1]
  21. previous = bigram[0][0]
  22. count = bigram[1]
  23. pos_current = vocab_index[current]
  24. pos_previous = vocab_index[previous]
  25. co_occurrence_matrix[pos_current][pos_previous] = count
  26. co_occurrence_matrix = np.matrix(co_occurrence_matrix)
  27. # return the matrix and the index
  28. return co_occurrence_matrix, vocab_index
  29. text_data = [['Where', 'Python', 'is', 'used'],
  30. ['What', 'is', 'Python' 'used', 'in'],
  31. ['Why', 'Python', 'is', 'best'],
  32. ['What', 'companies', 'use', 'Python']]
  33. # Create one list using many lists
  34. data = list(itertools.chain.from_iterable(text_data))
  35. matrix, vocab_index = generate_co_occurrence_matrix(data)
  36. data_matrix = pd.DataFrame(matrix, index=vocab_index,
  37. columns=vocab_index)
  38. print(data_matrix)

OutPut

  1. best use What Where ... in is Python used
  2. best 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 1.0
  3. use 0.0 0.0 0.0 0.0 ... 0.0 1.0 0.0 0.0
  4. What 1.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
  5. Where 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
  6. Pythonused 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 1.0
  7. Why 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 1.0
  8. companies 0.0 1.0 0.0 1.0 ... 1.0 0.0 0.0 0.0
  9. in 0.0 0.0 0.0 0.0 ... 0.0 0.0 1.0 0.0
  10. is 0.0 0.0 1.0 0.0 ... 0.0 0.0 0.0 0.0
  11. Python 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
  12. used 0.0 0.0 1.0 0.0 ... 0.0 0.0 0.0 0.0
  13. [11 rows x 11 columns]

使用 TextBlob 进行情感分析(???)

  1. from textblob import TextBlob
  2. def sentiment(polarity):
  3. if blob.sentiment.polarity < 0:
  4. print("Negative")
  5. elif blob.sentiment.polarity > 0:
  6. print("Positive")
  7. else:
  8. print("Neutral")
  9. blob = TextBlob("The movie was excellent!")
  10. print(blob.sentiment)
  11. sentiment(blob.sentiment.polarity)
  12. blob = TextBlob("The movie was not bad.")
  13. print(blob.sentiment)
  14. sentiment(blob.sentiment.polarity)
  15. blob = TextBlob("The movie was ridiculous.")
  16. print(blob.sentiment)
  17. sentiment(blob.sentiment.polarity)

OutPut

  1. Sentiment(polarity=1.0, subjectivity=1.0)
  2. Positive
  3. Sentiment(polarity=0.3499999999999999, subjectivity=0.6666666666666666)
  4. Positive
  5. Sentiment(polarity=-0.3333333333333333, subjectivity=1.0)
  6. Negative

使用 Goslate 进行语言翻译

  1. import goslate
  2. text = "Comment vas-tu?"
  3. gs = goslate.Goslate()
  4. translatedText = gs.translate(text, 'en')
  5. print(translatedText)
  6. translatedText = gs.translate(text, 'zh')
  7. print(translatedText)
  8. translatedText = gs.translate(text, 'de')
  9. print(translatedText)

使用 TextBlob 进行语言检测和翻译

  1. from textblob import TextBlob
  2. blob = TextBlob("Comment vas-tu?")
  3. print(blob.detect_language())
  4. print(blob.translate(to='es'))
  5. print(blob.translate(to='en'))
  6. print(blob.translate(to='zh'))

OutPut

  1. fr
  2. ¿Como estas tu?
  3. How are you?
  4. 你好吗?

使用 TextBlob 获取定义和同义词

  1. from textblob import TextBlob
  2. from textblob import Word
  3. text_word = Word('safe')
  4. print(text_word.definitions)
  5. synonyms = set()
  6. for synset in text_word.synsets:
  7. for lemma in synset.lemmas():
  8. synonyms.add(lemma.name())
  9. print(synonyms)

OutPut

  1. ['strongbox where valuables can be safely kept', 'a ventilated or refrigerated cupboard for securing provisions from pests', 'contraceptive device consisting of a sheath of thin rubber or latex that is worn over the penis during intercourse', 'free from danger or the risk of harm', '(of an undertaking) secure from risk', 'having reached a base without being put out', 'financially sound']
  2. {'secure', 'rubber', 'good', 'safety', 'safe', 'dependable', 'condom', 'prophylactic'}

使用 TextBlob 获取反义词列表

  1. from textblob import TextBlob
  2. from textblob import Word
  3. text_word = Word('safe')
  4. antonyms = set()
  5. for synset in text_word.synsets:
  6. for lemma in synset.lemmas():
  7. if lemma.antonyms():
  8. antonyms.add(lemma.antonyms()[0].name())
  9. print(antonyms)

OutPut

  1. {'dangerous', 'out'}