使用 ord 和 chr 移动字母

2023-12-03

我正在尝试执行一个函数,将每个单词中的每个字母按值向右移动 这些单词将来自一个列表,我将使用“打开”功能打开它 我写了代码,我在这里面临一些困难 这是我的代码

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)

这是我得到的输出

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

我有以下单词的列表 苹果 橙子 西瓜 猕猴桃 夏南瓜 胡萝卜 秋葵 辣椒 胡椒 黄瓜 香蕉 当我使用这段代码时

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)

我得到这个输出

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
>>> 

我在这里做错了什么?以及最好使用哪个代码以使其正常工作

Thanks


虽然您的方法总体上走在正确的轨道上,但正如其他人指出的那样,它存在一些问题。由于您似乎无法理解该做什么以及如何解决问题,因此我整理了您的代码(到处进行了一些编辑)并详细记录了我对代码的编辑,以便您可以了解什么方法应该是:

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

这种方法的唯一问题是它不是循环的(即 - 它不会循环回来:例如z移动了3不会成为c),因为这些值将超出其各自字符集的上限(如下面的输出部分所示)。而且,如果输入的值非常大(即大于您正在使用的字符集的范围),您会得到乱码。

但是,我不知道这是否是您问题的要求(这可能不是因为您基本上是按照您之前的问题所建议的方式对密码进行原始加密),但我想我还是会提到。

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 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ord 和 chr 移动字母 的相关文章

随机推荐

  • 在javascript中移动对象元素位置

    我正在尝试找到一种将对象元素移动到特定位置的方法 例如 我有这个对象 element1 object element2 element3 我搜索将 element3 移动到第一个位置 element3 element1 element2 感
  • 从 PDO 准备好的语句中获取原始 SQL 查询字符串

    在准备好的语句上调用 PDOStatement execute 时 有没有办法让原始 SQL 字符串执行 出于调试目的 这将非常有用 我假设您的意思是您想要最终的 SQL 查询 并将参数值插入其中 我知道这对于调试很有用 但这不是准备好的语
  • 如何为等待函数调用添加超时

    向等待函数添加超时的最佳方法是什么 Example lets pretend this is in a library that I m using and I can t mess with the guts of this thing
  • 按平均值排名的箱线图

    我想显示多个变量的箱线图 并按列均值降序排列它们 就像在绩效分析包裹 我使用以下代码生成箱线图 zx lt replicate 5 rnorm 50 zx means lt colMeans zx na rm TRUE boxplot zx
  • django 和 facebook:代表用户执行第三方登录的 facebook web 应用程序的安全性和设计

    我正在编写一个 Facebook 画布 Web 应用程序 它执行对第三方网站的登录 使用 urllib 并代表用户执行操作 这意味着我有2个账户 用户在我的网络应用程序中拥有的帐户 通过 facebook 以及应用程序用来代表他们执行登录的
  • Android Parcelable 对象返回 Null

    我有产品类 我想将产品对象从一项活动传递到另一项活动 我已经这样实现了 public class Product implements Parcelable private double availableQuantity private
  • 函数修改列表

    def make Ab A b n len A Ab list A for index in range 0 n Ab index append b index 0 print A return Ab copy A 0 0 1 0 1 0
  • VSCode 片段触发器之前有文本吗?

    我想在 VSCode 中创建一个显示 PHP 箭头的代码片段 当我按 键然后按 TAB 键时 我想要 PHP 箭头 gt 这是我的代码片段 PHP arrow prefix body gt 0 description PHP Arrow g
  • R - 将数据帧转换为格式为 featureName:featureValue [重复] 的数据集

    这个问题在这里已经有答案了 原来我想要的格式叫 SVM 轻 并在这里描述http svmlight joachims org 我有一个数据框 我想将其转换为格式如下的文本文件 output featureIndex featureValue
  • 无法在子进程命令中使用 grep

    我的子进程命令有问题 我喜欢 grep 出与 Online 行匹配的行 def run command command p subprocess Popen command shell False stdout subprocess PIP
  • 如何处理 tokio::spawn 闭包需要“static”和“&self”?

    我无法理解如何编写封装在一个结构中的并发异步代码 我不确定如何准确解释这个问题 所以我会尝试用一个例子来解释 假设我有一个UdpServer结构 该结构有多个与其行为相关的方法 例如 handle datagram deserialize
  • 我们是否忽略补码的溢出

    我试图解决二进制补码内的溢出问题 例如说我试图去掉这两个二进制数 1111 1000 0100 010 111 001 000 我将第二个二进制数转换为两个补码等值 然后简单地将其相加 但我注意到它导致了 1 的溢出 我是否只是忽略溢出 或
  • 未找到 Python 模块,但该模块存在于文件夹中

    我正在尝试执行一个简单的 PY 文件 但收到以下错误 Traceback most recent call last File docker pull py line 8 in
  • Python 中可能存在混合缩进吗?

    看着this问题 我在我的机器上尝试了OP的代码 这里有一个文字版和截图 刚刚发生了什么 这应该是一个square功能 并且已正确实现 可以肯定的是 我复制粘贴了代码 然后再次尝试 好吧 我看不出这些版本之间有什么区别square 但只有后
  • 使用 clusplot 绘制以 0 为中心坐标的聚类

    我正在尝试绘制 GIS 坐标 特别是东向和北向相似的英国国家网格坐标 194630000 562220000 我可以使用 Cluster 库中的 clusplot 绘制这些图 clusplot df2 k means fit cluster
  • Javascript 函数生成具有非均匀概率的随机整数

    在javascript 或jquery 中 有一个简单的函数可以计算四个整数及其概率值 1 0 41 2 0 29 3 0 25 4 0 05 我怎样才能生成这四个数字并考虑到它们的概率 这个问题与这里发布的问题非常相似 生成具有概率的随机
  • php 5.3.1 的 phpinfo() 中未启用 mysql

    我在 Vista 上安装了 apache 2 2 14 php 5 3 1 和 mysql 5 1 43 两天以来我一直在尝试配置 php 以在 phpinfo 上启用 mysql 我修改了 php ini 使其具有 extension d
  • 惰性类属性装饰器

    我有一个 Django 模型 需要对自定义用户模型进行一些处理 我无法在类加载时使用该模型的类 因为类的加载顺序未知 所以我需要在运行时添加一些类属性 目前我将它们添加到 init or new like def new cls args
  • SQL Server 对浮点字段“like”会产生不一致的结果

    我在用LIKE返回针对浮点字段的匹配数字结果 似乎一旦小数点左侧超过 4 位 则不会返回与我的小数点右侧搜索项匹配的值 下面是一个说明这种情况的示例 CREATE TABLE number like test num FLOAT NULL
  • 使用 ord 和 chr 移动字母

    我正在尝试执行一个函数 将每个单词中的每个字母按值向右移动 这些单词将来自一个列表 我将使用 打开 功能打开它 我写了代码 我在这里面临一些困难 这是我的代码 def test value eval input Value here wit