2017-05-03 39 views
1

我擁有一組文本。這些文本中的每一個都進行了規範化並標記爲一個列表 - 我將在下面發佈該代碼 - 以便我擁有的是列表的列表,其中每個列表都是文本。我想要做的是在文本中獲取每個單詞的所有位置。Python:將項目的位置以列表索引的百分比除以長度

例如,「這是一個文本;它不是一個長文本。」

here: 1  (Not counting pythonically here.) 
is: 2, 6 
a: 3, 8 
text: 4, 10 
it: 5 
not: 7 
long: 9 

這些位置,但是,沒有可比性,所以我想通過將它們除以文本的長度正常化他們:

here: 0.1 
is: 0.2, 0.6 

我的目標是便能收集up 全部跨文本集合中的這些詞的實例並且平均位置以便查看文本的特定部分中是否經常出現某些詞。這是什麼David Robinson has done in R。我試圖做到這一點在Python:

# =-=-=-=-=-=-=-=-=-=-= 
# Data Load & Tokenize 
# =-=-=-=-=-=-=-=-=-=-= 

import pandas 
import re 
from nltk.tokenize import WhitespaceTokenizer 

# LOAD 
colnames = ['author', 'title', 'date' , 'length', 'text'] 
df = pandas.read_csv('../data/talks_3.csv', names=colnames) 
talks = df.text.tolist() 
authors = df.author.tolist() 
dates = df.date.tolist() 
years = [re.sub('[A-Za-z ]', '', item) for item in dates] 
authordate = [author+" "+year for author, year in zip(authors, years)] 

# TOKENIZE 
tokenizer = WhitespaceTokenizer() 
texts = [] 
for talk in talks: 
    raw = re.sub(r"[^\w\d'\s]+",'', talk).lower() 
    tokens = tokenizer.tokenize(raw) 
    texts.append(tokens) 

,這裏是我偶然在那裏 - 它會從工作中以僞代碼很快:

def get_word_placement(listname): 
    wordplaces = {} 
    for word in listname: 
     get the word 
     get its location of listname[word]/len(listname) 
     attach those locations to word 

回答

1

如果enumerate列表,然後你有索引,並且可以通過長度除以獲得相對位置:

代碼:

word_list = 'Here is a text it is not a long text'.split() 
print(word_list) 

word_with_position = [ 
    (word, float(i)/len(word_list)) for i, word in enumerate(word_list)] 
print(word_with_position) 

結果:

['Here', 'is', 'a', 'text', 'it', 'is', 'not', 'a', 'long', 'text'] 

[('Here', 0.0), ('is', 0.1), ('a', 0.2), ('text', 0.3), ('it', 0.4), 
('is', 0.5), ('not', 0.6), ('a', 0.7), ('long', 0.8), ('text', 0.9)] 

作爲字典:

from collections import defaultdict 

word_with_positions = defaultdict(list) 
for i, word in enumerate(word_list): 
    word_with_positions[word].append(float(i)/len(word_list)) 

print(word_with_positions) 

結果:

{'a': [0.2, 0.7], 'text': [0.3, 0.9], 'is': [0.1, 0.5], 'it': [0.4], 
'Here': [0.0], 'long': [0.8], 'not': [0.6]} 
+0

尼斯。好吧,我會嘗試一下,看看我是否可以編譯元組列表,以便每個單詞只出現在具有多個位置的列表中 - 我必須爲單個文本或整個整個語料庫。 –

+1

你打敗了我。非常感謝! –

相關問題