2015-04-26 1 views
0

На самом деле я исхожу из C++, и я тоже здесь новый, у меня проблема с итерацией. Я использую python 2.7.8 и не могу решить, что именно я хочу. У меня есть имя файла под названием «foo.txt». Через код я пытаюсь найти, используя количество «a e i o u» в файле. Я создал массив: vowel [] = {'a', 'e', ​​'i', 'o', u}, и мой код должен дать мне комбинацию всех гласных. Но я столкнулсякак искать символ из файла в python

ошибку:

TypeError: list indices must be integers, not str 

файл foo.txt

Chronobiology might sound a little futuristic – like something from a science fiction novel, perhaps – but it’s actually a field of study that concerns one of the oldest processes life on this planet has ever known: short-term rhythms of time and their effect on flora and fauna. 

This can take many forms. Marine life, for example, is influenced by tidal patterns. Animals tend to be active or inactive depending on the position of the sun or moon. Numerous creatures, humans included, are largely diurnal – that is, they like to come out during the hours of sunlight. Nocturnal animals, such as bats and possums, prefer to forage by night. A third group are known as crepuscular: they thrive in the low-light of dawn and dusk and remain inactive at other hours. 

When it comes to humans, chronobiologists are interested in what is known as the circadian rhythm. This is the complete cycle our bodies are naturally geared to undergo within the passage of a twenty-four hour day. Aside from sleeping at night and waking during the day, each cycle involves many other factors such as changes in blood pressure and body temperature. Not everyone has an identical circadian rhythm. ‘Night people’, for example, often describe how they find it very hard to operate during the morning, but become alert and focused by evening. This is a benign variation within circadian rhythms known as a chronotype. 

мой код:

fo = open("foo.txt", "r") 
count = 0 
for i in fo: 
    word = i 
    vowels = ['a','e','i','o','u','y'] 
    word = word.lower().strip(".:;?!") 
#print word 
for j in word: # wanting that loop shd iterate till the end of file 
    for k in vowels: # wanting to index string array until **vowels.length()** 
     if (vowels[k] == word[j]): 
      count +=1 


#print word[0]  
print count 
+0

Существует почти никогда не является причиной для индекса в строку в цикле в Python - вы могут просто перебирать их напрямую. I.e .: 'для символа в слове:'. – jwilner

+0

Здесь 'word' - это строка, а не слово из файла' foo.txt'. –

ответ

1

ли в диапазоне (LEN()) вместо того, чтобы, потому что если вы используете for k in vowels, k будет «a», затем «b», затем «c» ... и т. д. Однако t синтаксис для получения объектов по индексам - гласные [index_number], а не гласные [содержание]. Таким образом, вы должны пройти по длине массива, и использовать гласные [0], чтобы получить «а», то гласные [1], чтобы получить „б“ и т.д.

fo = open("foo.txt", "r") 
count = 0 
for i in fo: 
    word = i 
    vowels = ['a','e','i','o','u','y'] 
    word = word.lower().strip(".:;?!") 
#print word 

    for j in range(len(word)): # wanting that loop shd iterate till the end of file 
     if (word[j] in vowels): 
       count +=1 


#print word[0]  
print count 
+0

спасибо, но я получаю меньший счет, который составляет 206, а фактический подсчет составляет более 400. Любая идея? –

+0

проблема с чтением файла? –

+0

Действительно ли идентификация? Я скорректировал код, чтобы проверить его. – RafaelC

1

Python гордится своей абстракции и стандартных библиотечных структур данных. Выезд collections.Counter. Он принимает итерируемый и возвращает значение переменной ->.

with open('foo.txt') as f: 
    string = f.read() 

counter = collections.Counter(string) # a string is an iterable of characters 
vowel_counts = {vowel: counter[vowel] for vowel in "aeiou"} 
2

Python есть замечательный модуль под названием collections с функцией Counter. Вы можете использовать его как это:

import collections 
with open('foo.txt') as f: 
    letters = collections.Counter(f.read()) 
vowels = ['a','e','i','o','u','y'] 
## you just want the sum 
print(sum(letters[vowel] for vowel in vowels)) 

Вы также можете сделать это без collections.Counter():

import itertools 
vowels = {'a','e','i','o','u','y'} 
with open("foo.txt") as f: 
    print(sum(1 for char in itertools.chain.from_iterable(f) if char in vowels)) 

Пожалуйста, обратите внимание, что временная сложность набора {} поиска является O(1), а временной сложности для списка [] поиск O(n) согласно this page on wiki.python.org.

Я протестировал оба метода с модулем timeit и, как ожидается, первый метод, использующий collections.Counter() немного быстрее:

0.13573385099880397 
0.16710168996360153 
+0

спасибо, но я также попытался найти согласные и, следуя за тобой, дал мне ошибку TypeError: unhashable type: 'list' импортные коллекции с открытым ('foo.txt') как f: letters = collections.Counter (ф.read()) vowels = ['a', 'e', ​​'i', 'o', 'u'] consonants = ['b', 'c', 'd', 'f', 'g », 'ч', 'J', 'к', 'L', 'M', 'N', 'р', 'Q', 'R', 'S', 'T', 'V', 'w', 'x', 'y', 'z'] ## вы просто хотите получить сумму печать (сумма (буквы [гласные] для гласного в гласных)) печать согласные печать (сумма [ согласные] для v в согласных)) –

+0

Вам нужно сделать 'print (sum (буквы [v] для v в согласных))' –

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