2017-04-06 42 views
1

我想写一个凯撒密码,但比正常情况下更难。实际的加密是在一个文件上,然后被分割成几行。对于每一行,我希望在开始,中间和结束之前添加一个单词,然后再进行转换。到目前为止,我有这一点,但它不工作:如何找到字符串的中间插入一个词

file = str(input("Enter input file:" "")) 
my_file = open(file, "r") 
file_contents = my_file.read() 
#change all "e"s to "zw"s 
    for letter in file_contents: 
     if letter == "e": 
      file_contents = file_contents.replace(letter, "zw") 
#add "hokie" to beginning, middle, and end of each line 
    lines = file_contents.split('\n') 
     def middle_message(lines, position, word_to_insert): 
      lines = lines[:position] + word_to_insert + lines[position:] 
      return lines 
     message = "hokie" + middle_message(lines, len(lines)/2, "'hokie'") + "hokie" 

我越来越

TypeError: slice indices must be integers or None or have an __index__ method 

我在做什么错了,我还以为LEN()返回一个int?

+1

在Python 3.x,'len(lines)/ 2'可能不是一个整数... – jonrsharpe

回答

1

假设即使固定LEN()不是一个整数后您使用python3

您将需要一些更多的优化。

让我们的工作了这一点,第一:我们的例子中字是:

a = 'abcdef' 
>>> len(a) 
6 
>>> len(a)/2 
3.0 #this is your problem, dividing by 2 returns a float number 

你所得到的错误是因为浮点数(3.0和3.5),不能在列表中使用的切片索引(或字符串),解决了这个在这种特殊情况下:现在

>>> len(a) // 2 
3 

,优化:

此代码需要一个文件,我认为是由文本的许多行,因为你是使用'\ n'分割线条。

当你已经解决了片部分,你会得到另一个错误,告诉你不能连接使用列表字符串(你应该在这一点上,试试你的代码我上面提出的修正,所以你明白什么发生)

您的middle_message函数被设置为使用单个字符串,但是您将它传递给变量'lines',这是一个字符串列表。

测试,我不得不把它传递线的指标:如果你想在“行”,所有的字符串列表理解循环可能是有用的工作

message = "hokie" + middle_message(lines[0], len(lines[0])//2, "hokie") + "hokie" 

所以,给你一个新的列出您的修改过的字符串。

newlines = ["hokie" + middle_message(lines[x], len(lines[x])//2, "hokie") + "hokie" for x in range(len(lines))] 

我知道,这是超过80个字符..你可以工作下来我敢肯定;)

现在这里的结果我得到测试:

>>> file_contents 
'This is going to be my test file\nfor checking some python cipher program.\ni want to see how it works.\n' 

>>> lines 
['This is going to bzw my tzwst filzw', 'for chzwcking somzw python ciphzwr program.', 'i want to szwzw how it works.', ''] 

>>> newlines 
['hokieThis is going to hokiebzw my tzwst filzwhokie', 'hokiefor chzwcking somzw phokieython ciphzwr program.hokie', 'hokiei want to szwzhokiew how it works.hokie', 'hokiehokiehokie'] 
相关问题