Do you know of the JieBa pip?
- User
Do you know of the JieBa pip?
- Assistant
Yes, Jieba is a popular Python library used for natural language processing tasks in Chinese text, including tokenization, part-of-speech tagging, and sentiment analysis. It can be installed and managed using pip, the package installer for Python.
- User
I want you to help me write the Python3 to be used for analyzing of Chinese text. What this should do is take in a txt file then segment the words using Jieba and list all vocabularies used in the text in order of frequency along with how many times it is used.
- Assistant
Sure, here’s a sample code snippet that reads in a text file in Chinese, segments the words using Jieba and lists the vocabulary used in the text in order of frequency along with how many times each one is used.
import jieba # Open the input file and read in the text input_file = open('input_file.txt', 'r', encoding='utf-8') text = input_file.read() # Segment the words using Jieba seg_list = jieba.lcut(text) # Create a dictionary to store the frequency counts vocab_counts = {} # Loop through the segments and count the frequency of each word for word in seg_list: if word not in vocab_counts: vocab_counts[word] = 1 else: vocab_counts[word] += 1 # Sort the dictionary by word frequency in descending order sorted_vocab_counts = sorted(vocab_counts.items(), key=lambda item:item[1], reverse=True) # Print the sorted vocabulary list with word frequency counts for item in sorted_vocab_counts: print(item[0], item[1]) - User
Need not send the whole code back again but make it so that it output as a txt, also format the output properly with number of frequency aligning
- Assistant
No problem! Here is the revised code:
import jieba # Open the input file and read in the text input_file = open('input_file.txt', 'r', encoding='utf-8') text = input_file.read() # Segment the words using Jieba seg_list = jieba.lcut(text) # Create a dictionary to store the frequency counts vocab_counts = {} # Loop through the segments and count the frequency of each word for word in seg_list: if word not in vocab_counts: vocab_counts[word] = 1 else: vocab_counts[word] += 1 # Sort the dictionary by word frequency in descending order sorted_vocab_counts = sorted(vocab_counts.items(), key=lambda item:item[1], reverse=True) # Save the sorted vocabulary list with word frequency counts to a new text file with open('output_file.txt', 'w', encoding='utf-8') as output_file: for item in sorted_vocab_counts: output_file.write(item[0] + ' '*(30-len(item[0])) + str(item[1]) + '\n')