gpt4 book ai didi

python - 从词频创建 ARFF

转载 作者:太空狗 更新时间:2023-10-30 01:35:20 25 4
gpt4 key购买 nike

我有一些代码可以给我一个单词列表以及它们在文本中出现的频率,我正在寻找它以便代码自动将前 10 个单词转换为 ARFF

@RELATION 词频

@ATTRIBUTE 字串@ATTRIBUTE 频率数字

前 10 名作为数据及其频率。

我正在为如何使用我当前的代码执行此操作而苦苦挣扎

import re
import nltk

# Quran subset
filename = 'subsetQuran.txt'

# create list of lower case words
word_list = re.split('\s+', file(filename).read().lower())
print 'Words in text:', len(word_list)

word_list2 = [w.strip() for w in word_list if w.strip() not in nltk.corpus.stopwords.words('english')]



# create dictionary of word:frequency pairs
freq_dic = {}
# punctuation and numbers to be removed
punctuation = re.compile(r'[-.?!,":;()|0-9]')
for word in word_list2:
# remove punctuation marks
word = punctuation.sub("", word)
# form dictionary
try:
freq_dic[word] += 1
except:
freq_dic[word] = 1


print '-'*30

print "sorted by highest frequency first:"
# create list of (val, key) tuple pairs
freq_list2 = [(val, key) for key, val in freq_dic.items()]
# sort by val or frequency
freq_list2.sort(reverse=True)
freq_list3 = list(freq_list2)
# display result
for freq, word in freq_list2:
print word, freq
f = open("wordfreq.txt", "w")
f.write( str(freq_list3) )
f.close()

感谢任何对此的帮助,这样做的方式真的让我绞尽脑汁!

最佳答案

我希望你不介意轻微的重写:

import re
import nltk
from collections import defaultdict

# Quran subset
filename = 'subsetQuran.txt'

# create list of lower case words
word_list = open(filename).read().lower().split()
print 'Words in text:', len(word_list)

# remove stopwords
word_list = [w for w in word_list if w not in nltk.corpus.stopwords.words('english')]

# create dictionary of word:frequency pairs
freq_dic = defaultdict(int)

# punctuation and numbers to be removed
punctuation = re.compile(r'[-.?!,":;()|0-9]')
for word in word_list:
# remove punctuation marks
word = punctuation.sub("", word)
# increment count for word
freq_dic[word] += 1

print '-' * 30

print "sorted by highest frequency first:"
# create list of (frequency, word) tuple pairs
freq_list = [(freq, word) for word, freq in freq_dic.items()]

# sort by descending frequency
freq_list.sort(reverse=True)

# display result
for freq, word in freq_list:
print word, freq

# write ARFF file for 10 most common words
f = open("wordfreq.txt", "w")
f.write("@RELATION wordfrequencies\n")
f.write("@ATTRIBUTE word string\n")
f.write("@ATTRIBUTE frequency numeric\n")
f.write("@DATA\n")
for freq, word in freq_list[ : 10]:
f.write("'%s',%d\n" % (word, freq))
f.close()

关于python - 从词频创建 ARFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5500482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com