2014-10-31 6 views
0

Я пытаюсь создать набор слов, что означает строго только алфавиты из .txt-файла. Этот txt-файл содержит все возможные символы, в том числе непечатаемый текст.Наборы слов из текстового файла

Нет библиотек re или collection. Python 3

Например, учитывая .txt файл, который читает

*eBooks$ Readable By Both Humans and By Computers, Since 1971** 

*These# [email protected] Were Prepared By Thousands of Volunteers! 

Я бы нужны мои наборы содержат

{'eBooks', 'Readable', 'By', 'Both', 'Humans', 'and', 'Computers', 'Since', 'These', 'Were', 'Prepared', 'Thousands', 'of', 'Volunteers'} 

Вот то, что я сделал, но я все еще получаю специальные символы и цифры на моих наборах. Я только хочу алфавиты

import string 
filecontent = [] 
word_set = {} 
with open ("small.txt") as myFile: 
    for line in myFile: 
     line = line.rstrip() 
     line = line.replace("\t","") 
     for character in line: 
      if character in string.digits or character in string.punctuation: 
       line = line.replace(character, "") 
      if line != "": 
       filecontent.append(line) 
lowerCase = [x.lower() for x in filecontent] 
word_set = {word for line in lowerCase for word in line.split()} 
+0

Могу ли я спросить, почему вы исключаете ответы, используя MODULS с проверенные в использовании методы, сделанные точно для ваша? –

+0

Делает вопрос? и как насчет слова вроде «есть»? –

+0

@PadraicCunningham Cunningham Хорошо иметь и заказать не имеет значения с момента его набора –

ответ

2

Вы можете сделать что-то вроде этого:

>>> from string import punctuation 
>>> def solve(s): 
     for line in s.splitlines(): 
      for word in line.split(): 
       word = word.strip(punctuation) 
       if word.translate(None, punctuation).isalpha(): 
        yield word 
...     
>>> s = '''*eBooks$ Readable By Both Humans and By Computers, Since 1971** 

*These# [email protected] Were Prepared By Thousands of Volunteers!''' 
>>> set(solve(s)) 
set(['and', 'Both', 'Since', 'These', 'Readable', 'Computers', 'Humans', 'Prepared', 'of', 'Were', 'Volunteers', 'Thousands', 'By', 'eBooks']) 

Если вы используете Python 3, то вам нужно заменить str.translate часть с:

table = dict.fromkeys(map(ord, punctuation)) #add this at the top of function 
... 
if word.translate(table).isalpha(): 
    ... 
+0

вам нужно будет обновить строку перевода для python 3 –

+0

@PadraicCunningham Спасибо за обновление, добавлено исправление, связанное с Python 3. –

0

Вот решение с использованием модуля regex re. Он также предоставляет количество слов, но если вы не хотите, чтобы вы могли просто использовать ключи или заменить их на набор.

text = """*eBooks$ Readable By Both Humans and By Computers, Since 1971** 

*These# [email protected] Were Prepared By Thousands of Volunteers!""" 

import re 

from collections import Counter 

words = Counter() 

regex = re.compile(r"[a-zA-Z]+") 

matches = regex.findall(text) 
for match in matches: 
    words[match.lower()] += 1 

print words 

Или, если у вас есть это в файле;

with open("fileName") as textFile: 
    text = "".join(textFile.readLines()) #Necesary to turn the file into one long string, rather than an array of lines. 
    matches = regex.findall(text) 
    for match in matches: 
    words[match.lower()] += 1 

Что дает

Counter({'by': 3, 'ebooks': 2, 'and': 1, 'both': 1, 'since': 1, 'these': 1, 'readable': 1, 'computers': 1, 'humans': 1, '1971': 1, 'prepared': 1, 'of': 1, 'were': 1, 'volunteers': 1, 'thousands': 1}) 
0

Если бы я тебя я использовал re.findall

import re 
s = '''*eBooks$ Readable By Both Humans and By Computers, Since 1971** 
*These# [email protected] Were Prepared By Thousands of Volunteers!''' 
set(re.findall('[a-zA-Z]+',s)) 

выход

set(['and', 'Both', 'Since', 'These', 'Readable', 'Computers', 'Humans', 'Prepared', 'of', 'Were', 'Volunteers', 'Thousands', 'By', 'eBooks']) 
+0

Это не будет работать для слов с пунктуацией, например: 'can't' , –

Смежные вопросы