本文介绍了使用ord和chr来移动字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个函数,将每个单词中的每个字母按值
转移到右侧,这些单词将来自我将使用open函数打开它的列表
我写了代码和我在这里面临一些困难
这里是我的代码

  def test():
值= eval(输入(Value here!))
with open(word-text.txt,r)为f:
ford(f):
打印(ord)
用于chr in ord:
print(chr)
#nice =(chr [len(ord)+ value])
''.join([ (i)
print(i)

这是我得到的输出

 这里的值!2 
苹果

a
p
p

e
s


追溯(最近一次调用最后一次):
文件< pyshell#54> ;,第1行,在< module>
test()
文件/Users/user/Desktop/Outlook(1)/lab6.py,line 59,in test
''.join([chr(ord(i )+2)for i in s])
NameError:全局名称's'未定义

我有以下单词的名单:
苹果
橙子
西瓜
奇异果
西葫芦b
胡萝卜
秋葵
墨西哥胡椒
胡椒
黄瓜
香蕉
当我使用这段代码时

  ef test():
value = eval(input(Value here!))
with open(word-text.txt,r)as f:
for ord在(f)中:
print(ord)
for chr in ord:
print(chr)
nice =(chr [len(ord)+ value])
print(nice)

我得到这个输出

 值在这里!2 
苹果

a
追溯(最近一次调用最后):
文件< pyshell #56>,第1行,在< module>
test()
文件/Users/user/Desktop/Outlook(1)/lab6.py,第58行,在测试
nice =(chr [len(ord)+ value ])
IndexError:字符串索引超出范围
>>>

我在这里做错了什么?和哪个代码最好使用,以便它能够正常工作



谢谢

解决方案

虽然你的方法通常有点正确,但其他人已经注意到了它的一些问题。由于看起来您无法理解要做什么以及如何解决问题,因此我已经整理了您的代码(在此处进行了一些编辑),并大量记录了我对代码的编辑,以便您能够理解该方法应该是:

$ pre $ def $ test $ b $ value = input(Value here!)#eval是不好的和危险的做法。避免使用它。
打开(word-text.txt,r)为f:
#此时您可以执行以下两项操作之一:
#1)读取整个文件行按行
#2)将整个文件读入列表中,并循环/遍历该列表
#在此示例中,我将逐行读取文件:
nice_strings = [ ]
for line in f:
line = line.strip()#从该行删除任何无关的空格(例如空格和换行符)
nice_str_chars = []
#在此点,您想要读取
#NB中的每个字符:ord是内置函数的名称。使用另一个名字,比如`char`(下面):
用于char:
#因为你在这个循环中,你正在处理每行的每个单独字符
#And,因为你想转移字符的一些地方
#Python不允许你本地移动字符串的任意数量,
#so,我们可以这样做的唯一方法是转换将每个字符转换为其数字表示形式。
#为了这样做,你必须使用`ord`函数将字符转换为
#它们各自的整数表示形式。
int_of_char = ord(char)
#在这一点上,该角色已被转换为相当于
#NOW的整数,您可以移动它。换句话说,将该值添加到int_of_char中:
int_of_char + = value #update变量
#的值此时,该值已被修改,字符的INTEGER值已经
#移动。但是,我们不希望移位的INTEGER值:我们想要移位的CHARACTER值。
#So,我们如何将整数转换为字符? Python有一个叫做`chr`的内建函数,
#就是这个功能。
#So,让我们使用`chr`将转移后的INTEGER转换为移位字符:
nice_char = chr(int_of_char)
#将原始字符和修改后的字符打印出来,以便查看内容字符串(这一步是可选的)
print char,'=>',nice_char
#在这一点上我们已经成功地移动了字符。但是,由于这只是原始
#string的一个字符,我们需要一种将更新后的字符保存为字符串的方式。有很多方法可以做到这一点。
#为了简单起见,我们可以使用一个`nice_str_chars`列表:
nice_str_chars.append(nice_char)
#在这一点上,我们已经围绕ONE LINE中的所有字符,已经计算并存储了同一行的移位
#characters。但是,由于我们已将字符存储在一个列表中:`nice_str_chars`,所以我们
#将其转换为字符串。我们可以在空字符串上使用`join`方法来做到这一点,
#`nice_str_chars`作为列表(因为我们想将列表中的字符连接成一个字符串):
nice_str =' '.join(nice_str_chars)
#并且,因为您想要移动所有行,您应该将更正后的行附加到列表中,以后可以返回
#returned:
nice_strings.append (nice_str)
#你可以根据需要打印出来:
print line,'=>',nice_str,'\\\
'
#此时,你已经成功循环在整个文件中,通过用户输入的整数量
#now来移动所有行,所有你需要做的就是返回它,或者用它们做别的事情(即把更新后的字符串写入另一个文件)。
#那部分,我会留给你的。
return nice_strings

这种方法唯一的问题是它不是圆形的(例如 - 它不回环绕:例如 z 移动 3 不会变成 c ),因为这些值将超过它们各自字符集的上限(如下面的OUTPUT部分所示)。而且,如果输入的值非常大(即大于你工作的字符集的范围,你会得到乱码。)然而,我不知道这是否是您的问题的要求(这可能不像您以前的问题所建议的那样基本上对密码进行了原始加密),但我认为我会提及



输出:

 值在这里!2 
a => c
p => r
p => r
l => n
e => g
s => u
apples => crrngu

o => q
r => t
a => c
n => p
g => i
e => g
s => u
oranges => qtcpigu

w => y
a => c
t => ; v
e => g
r => t
m => o
e => g
l => n
o => q
n => p
watermelon => ycvgtognqp

k => m
i => k
w => y
i = > k
ki wi => mkyk

z => |
u => w
c => e
c => e
h => j
i => k
n => p
i => k
zucchini => | weejkpk

c => e
a => c
r => t
r => t
o => q
t => v
carrot => ecttqv

o => q
k => m
r => t
a => c
okra => qmtc

j => l
a => c
l => n
a => c
p => r
e => g
n => p
o => q
jalapeno => lcncrgpq

p => r
e => g
p => r
p => r
e => g
r => t
胡椒粉=> rgrrgt

c => e
u => w
c => e
u => w
m => o
b => d
e => g
r => t
cucumber => ewewodgt

b => d
a => c
n => p
a => c
n => p
a => c
banana => dcpcpc


I am trying to do a function that shifts each letter in each word to the right by valueand these words will be from a list that I will open it using "open"functionI wrote the code, and I am facing some difficulties herehere is my code

def test():
value=eval(input("Value here!"))
with open ("word-text.txt","r") as f:
    for ord in (f):
        print (ord)
        for chr in ord:
            print (chr)
            #nice=(chr[len(ord)+value])
        ''.join([chr(ord(i)+2) for i in s])
        print (i)

this is the output I get

Value here!2
apples

a
p
p
l
e
s


Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    test()
  File "/Users/user/Desktop/Outlook(1)/lab6.py", line 59, in test
    ''.join([chr(ord(i)+2) for i in s])
NameError: global name 's' is not defined

the list that I have the following wordsapplesorangeswatermelonkiwizucchinicarrotokrajalapenopeppercucumberbananaand when I use this code

ef test():
value=eval(input("Value here!"))
with open ("word-text.txt","r") as f:
    for ord in (f):
        print (ord)
        for chr in ord:
            print (chr)
            nice=(chr[len(ord)+value])
            print (nice)

I get this output

Value here!2
apples

a
Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    test()
  File "/Users/user/Desktop/Outlook(1)/lab6.py", line 58, in test
    nice=(chr[len(ord)+value])
IndexError: string index out of range
>>>

What am I doing wrong here? and which code is best to use, to get it working

Thanks

解决方案

While your approach is generally on a somewhat right track, there are some problems with it as others have noted. Since it seems that you're having trouble understanding what to do and how to go about solving the problem, I've tidied your code (made a few edits here and there) and heavily documented my edit of your code so you can understand what the approach should be:

def test():
    value=input("Value here!") #eval is bad AND dangerous practice. Avoid using it.
    with open ("word-text.txt","r") as f:
        #At this point you can do one of two things:
        #1) read the entire file line by line
        #2) read the entire file into a list, and loop/iterate over that list
        #In this example, I'll read the file line by line:
        nice_strings = []
        for line in f:
            line = line.strip() #remove any extraneous whitespace from the line (e.g. spaces and newlines)
            nice_str_chars = []
            #At this point, you want to read EACH character in the line
            #N.B.: ord is the name of a built-in function. Use another name like `char` (below):
            for char in line:
                #Since you're in this loop, you are dealing with EACH individual character of each line
                #And, as you want to "shift" the character by some number of places
                #Python doesn't allow you to natively shift strings by arbitrary amounts,
                #so, the only way we can do so is to convert EACH character into its numeric representation.
                #In order to do so, you have to use the `ord` function which converts characters into
                #their respective integer representation.
                int_of_char = ord(char)
                #At this point, the character has been converted to it's integer equivalent
                #NOW, you can "shift" it. In other words, add the value to the `int_of_char`:
                int_of_char += value #update the value of the variable
                #At this point, the value has been modified, and the INTEGER value of the character has been
                #shifted. However, we don't want the shifted INTEGER value: we want the shifted CHARACTER value.
                #So, how do we convert integers to characters? Python has a builtin function called `chr` which
                #does exactly that.
                #So, let's convert the shifted INTEGER to a shifted CHARACTER using `chr`:
                nice_char = chr(int_of_char)
                #print it out the original and modified characters so you can see what's in the string (this step is optional)
                print char, '=>', nice_char
                #At this point we've successfully shifted the character. However, since this is just A character of the original
                #string, we need a way to save the updated characters as a string. There are a number of ways to do this.
                #For simplicity, we can use a list `nice_str_chars`:
                nice_str_chars.append(nice_char)
            #At this point we've looped over all the characters in ONE LINE, and we've calculated and stored the shifted
            #characters for that same line. However, since we've stored the characters in a list: `nice_str_chars`, we
            #have to convert it to a string. We can do that using the `join` method on an empty string, with
            #`nice_str_chars` as the list (as we want to join the characters of the list into a string):
            nice_str = ''.join(nice_str_chars)
            #And, since you want to shift ALL the lines, you ought to append the corrected line to a list that can later be
            #returned:
            nice_strings.append(nice_str)
            #you can print it out if necessary:
            print line, '=>', nice_str, '\n'
        #At this point, you've successfully looped over the entire file, shifted all lines by a user entered integer amount,
        #now, all you have to do is return it, or do something else with them (i.e. write the updated strings to another file).
        #That part, I'll leave up to you.
        return nice_strings

The only problem with this approach is that it is not circular (i.e. - it doesn't loop back around: e.g. z shifted by 3 does not become c), as the values will exceed the upper bound of their respective character set (as revealed in the OUTPUT section below). And, if the value entered is very large (i.e. greater than the bounds of the character set in which you're working, you'll get gibberish.

However, I don't know if that's a requirement of your problem (which may not be as you're basically doing a primitive encryption of passwords as suggested by your previous questions), but I thought that I'd mention in nonetheless.

OUTPUT:

Value here!2
a => c
p => r
p => r
l => n
e => g
s => u
apples => crrngu

o => q
r => t
a => c
n => p
g => i
e => g
s => u
oranges => qtcpigu

w => y
a => c
t => v
e => g
r => t
m => o
e => g
l => n
o => q
n => p
watermelon => ycvgtognqp

k => m
i => k
w => y
i => k
kiwi => mkyk

z => |
u => w
c => e
c => e
h => j
i => k
n => p
i => k
zucchini => |weejkpk

c => e
a => c
r => t
r => t
o => q
t => v
carrot => ecttqv

o => q
k => m
r => t
a => c
okra => qmtc

j => l
a => c
l => n
a => c
p => r
e => g
n => p
o => q
jalapeno => lcncrgpq

p => r
e => g
p => r
p => r
e => g
r => t
pepper => rgrrgt

c => e
u => w
c => e
u => w
m => o
b => d
e => g
r => t
cucumber => ewewodgt

b => d
a => c
n => p
a => c
n => p
a => c
banana => dcpcpc

这篇关于使用ord和chr来移动字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:12
查看更多