2015-02-09 5 views
0

Итак, я пытаюсь подсчитать anhCrawler и вернуть количество символов с пробелами и без пробелов с позицией «DEATH STAR» и вернуть его в реестре. Я тоже не могу правильно подсчитать числа. Пожалуйста помоги!Подсчитайте символы в строке

anhCrawler = """Episode IV, A NEW HOPE. It is a period of civil war. \ 
Rebel spaceships, striking from a hidden base, have won their first \ 
victory against the evil Galactic Empire. During the battle, Rebel \ 
spies managed to steal secret plans to the Empire's ultimate weapon, \ 
the DEATH STAR, an armored space station with enough power to destroy \ 
an entire planet. Pursued by the Empire's sinister agents, Princess Leia\ 
races home aboard her starship, custodian of the stolen plans that can \ 
save her people and restore freedom to the galaxy.""" 

theReport = """ 
This text contains {0} characters ({1} if you ignore spaces). 
There are approximately {2} words in the text. The phrase 
DEATH STAR occurs and starts at position {3}. 
""" 

def analyzeCrawler(thetext): 
numchars = 0 
nospacechars = 0 
numspacechars = 0 
anhCrawler = thetext 
word = anhCrawler.split() 
for char in word: 
    numchars = word[numchars] 
    if numchars == " ": 
     numspacechars += 1 
anhCrawler = re.split(" ", anhCrawler) 
for char in anhCrawler: 
    nospacechars += 1 
numwords = len(anhCrawler) 
pos = thetext.find("DEATH STAR") 
char_len = len("DEATH STAR") 
ds = thetext[261:271] 
dspos = "[261:271]" 

return theReport.format(numchars, nospacechars, numwords, dspos) 
print analyzeCrawler(theReport) 
+2

'Я не могу правильно правильно подсчитать числа.' Итак, каковы ожидаемые результаты и что вы сейчас получаете? – Marcin

+0

Правильный счетчик символов - 519, а число слов - 86. Я не знаю номер позиции. @Marcin –

+1

Вы пробовали с меньшим текстом? –

ответ

1

Здесь вы simplilfied версии вашей функции:

import re 

def analyzeCrawler2(thetext, text_to_search = "DEATH STAR"): 

    numchars = len(anhCrawler) 
    nospacechars = len(re.sub(r"\s+", "", anhCrawler)) 
    numwords = len(anhCrawler.split()) 
    dspos  = anhCrawler.find(text_to_search) 

    return theReport.format(numchars, nospacechars, numwords, dspos) 



print analyzeCrawler2(theReport) 


This text contains 520 characters (434 if you ignore spaces). 
There are approximately 87 words in the text. The phrase 
DEATH STAR occurs and starts at position 261. 

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

+0

Спасибо, Марсин. Это сработало отлично! Но можете ли вы сказать мне значение «\ s +»? –

2

Вы переоцениваете эту проблему.

Количество символов в строке (возвращает 520):

len(anhCrawler) 

Количество непробельных символов в строке (с использованием split, как с помощью split автоматически удаляет пробелы и join создает строку, без пробелов) (возвращает 434):

len(''.join(anhCrawler.split())) 

Поиск позиции "Звезда смерти" (возвращает 261):

anhCrawler.find("DEATH STAR") 
+0

'len (anhCrawler.split())' возвращает количество _words_, а не общее количество не-пробельные символы. –

+1

@ ÓscarLópez: вы правы! Спасибо! Я исправил это. – jrd1

+1

Интересно, что обход конструкции новой строки перед подсчетом символов примерно в два раза медленнее * ('sum (len (word) for word in anhCrawler.split())). – EOL

1

Прежде всего, вам нужно отстудить код внутри функции. Во-вторых ... ваш код может быть упрощена следующим образом:

theReport = """ 
    This text contains {0} characters ({1} if you ignore spaces). 
    There are approximately {2} words in the text. The phrase 
    DEATH STAR is the {3}th word and starts at the {4}th character. 
""" 

def analyzeCrawler(thetext): 

    numchars = len(anhCrawler) 
    nospacechars = len(anhCrawler.replace(' ', '')) 
    numwords = len(anhCrawler.split()) 

    word = 'DEATH STAR' 
    wordPosition = anhCrawler.split().index(word) 
    charPosition = anhCrawler.find(word) 

    return theReport.format(
     numchars, nospacechars, numwords, wordPosition, charPosition 
    ) 

Я изменил последние два format аргументы, потому что не было понятно, что вы имели в виду dspos, хотя, может быть, это очевидно, и я не вижу его , В любом случае я включил слово и позицию char вместо этого. Вы можете определить, какой из них вы хотели бы включить.

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