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

你打败了我。非常感谢! –