나는 유사성을 분석 할 필요가있는 수백 개의 txt 파일이있는 폴더가 있습니다. 다음은 유사성 분석을 실행하는 데 사용하는 스크립트의 예입니다. 결국 배열이나 행렬 등을 얻을 수 있습니다.임계 값을 사용하여 행렬 계수 계산
cos_similarity > 0.5
(또는 다른 임계 값을 사용하기로 결정했습니다.) 동일한 파일을 비교할 때 cos_similarity == 1
을 제거하면 얼마나 많은 쌍이 있는지 알고 싶습니다. , 당연하지.
두 번째로 파일 이름을 기준으로 이러한 쌍의 목록이 필요합니다.
1
및
이["doc1", "doc4"]
정말 당신의 도움을 주셔서 감사합니다 나는 조금에 어느 방향을 모르고 잃은 느낌으로 : 같은
은 그래서 예를 들어, 출력은 아래에 보일 것이다 가기.doc1 = "Amazon's promise of next-day deliveries could be investigated amid customer complaints that it is failing to meet that pledge."
doc2 = "The BBC has been inundated with comments from Amazon Prime customers. Most reported problems with deliveries."
doc3 = "An Amazon spokesman told the BBC the ASA had confirmed to it there was no investigation at this time."
doc4 = "Amazon's promise of next-day deliveries could be investigated amid customer complaints..."
documents = [doc1, doc2, doc3, doc4]
# In my real script I iterate through a folder (path) with txt files like this:
#def read_text(path):
# documents = []
# for filename in glob.iglob(path+'*.txt'):
# _file = open(filename, 'r')
# text = _file.read()
# documents.append(text)
# return documents
import nltk, string, numpy
nltk.download('punkt') # first-time use only
stemmer = nltk.stem.porter.PorterStemmer()
def StemTokens(tokens):
return [stemmer.stem(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
def StemNormalize(text):
return StemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
nltk.download('wordnet') # first-time use only
lemmer = nltk.stem.WordNetLemmatizer()
def LemTokens(tokens):
return [lemmer.lemmatize(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
from sklearn.feature_extraction.text import CountVectorizer
LemVectorizer = CountVectorizer(tokenizer=LemNormalize, stop_words='english')
LemVectorizer.fit_transform(documents)
tf_matrix = LemVectorizer.transform(documents).toarray()
from sklearn.feature_extraction.text import TfidfTransformer
tfidfTran = TfidfTransformer(norm="l2")
tfidfTran.fit(tf_matrix)
tfidf_matrix = tfidfTran.transform(tf_matrix)
cos_similarity_matrix = (tfidf_matrix * tfidf_matrix.T).toarray()
from sklearn.feature_extraction.text import TfidfVectorizer
TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
def cos_similarity(textlist):
tfidf = TfidfVec.fit_transform(textlist)
return (tfidf * tfidf.T).toarray()
cos_similarity(documents)
아웃 : 나는 당신의 질문을 알 수있는 바와 같이
array([[ 1. , 0.1459739 , 0.03613371, 0.76357693],
[ 0.1459739 , 1. , 0.11459266, 0.19117117],
[ 0.03613371, 0.11459266, 1. , 0.04732164],
[ 0.76357693, 0.19117117, 0.04732164, 1. ]])
보세요! 이전 스 니펫에서는 함수를 왼쪽 및 오른쪽으로 생성하고 있음을 알 수 있습니다. 같은 코드를 반복해서 사용하는 경우에만 함수를 작성하므로 시간과 노력을 절약 할 수 있습니다. 그러나 함수가 단지 한 줄이거나 한 번만 사용하면 더 깨끗하고 읽기 쉽고 이해하기 쉬운 코드를 만들지 않는 것이 좋습니다. –
당신은 절대적으로 옳습니다! 나는이 튜토리얼을 온라인 튜토리얼에서 가져 왔지만 당신이 제안한대로 정리할 것이다. – aviss
keep rockin ', bro –