所以我试着计算ancrawler,返回带空格和不带空格的字符数,以及“死星”的位置,并在报告中返回。我也数不清。请帮忙!在
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)
你想得太多了。
字符串中的字符数(返回520):
字符串中非空白字符的数目(使用
^{pr2}$split
与使用split
一样自动删除空白,join
创建一个没有空格的字符串)(返回434):“发现死亡之星的位置”(261):
在这里,您得到了函数的简化版本:
我认为技巧部分是从字符串中删除空格并计算非空格字符数。这可以通过使用正则表达式来实现。其余的应该是不言而喻的。在
首先,您需要缩进函数内部的代码。第二。。。您的代码可以简化为以下内容:
我修改了最后两个
format
参数,因为它不清楚你所说的dspos
是什么意思,尽管这可能很明显,我没有看到它。在任何情况下,我改为包含单词和字符位置。你可以决定你真正想要包括哪一个。在相关问题 更多 >
编程相关推荐