<p>我是python的超级新手。我有点困在课堂练习上了。
问题是这样的:您有一个包含字符(即单词)的文件。(我仍处于所有术语混淆的阶段,如果这不是正确的术语,我深表歉意)
示例文件.txt内容:accbd</p>
<p>这个问题要求我将文件导入到python编辑器中,并确保出现的字母不会超过字母表中出现的字母。e、 a不能比b频繁出现;b不能比c频繁出现,以此类推。在示例文件中,c出现的频率比d高,因此我需要发出一条错误消息。你知道吗</p>
<p>以下是我可怜的尝试:</p>
<pre><code>def main():
f=open('.txt','r') # 1st import the file and open it.
data = f.read() #2nd read the file
words = list(data) #3rd create a list that contains every letter
newwords = sorted(words) # sort according to alphabetical order
</code></pre>
<p>我被困在最后一部分,那就是计算前一个词不会比后一个词出现得更多,依此类推。我试过两种方法,但都不管用。以下是试验1:
从集合导入计数器</p>
<pre><code>for i in newwords:
try:
if counter(i) <=counter(i+1):
print 'ok'
else:
print 'not ok between indexes %d and %d' % (i, i+1)
except:
pass
</code></pre>
<p>第二次审判也是类似的</p>
<pre><code>for i in newwords:
try:
if newwords.count(i) <= newwords.count(i+1):
print 'ok'
else:
print 'ok between indexes %d and %d' % (i, i+1)
except:
pass
</code></pre>
<p>按顺序比较每个单词的计数的正确方法是什么?你知道吗</p>