通过逗号分隔的整数文件进行迭代以使用chr()函数

时间:2019-03-13 13:51:11

标签: python python-3.x

我目前正在尝试编写一段代码,该代码将允许我使用数字文件,并能够使用chr()函数将数字转换为与Unicode等价的数字。

这是我到目前为止所拥有的:

readFile = "numbers.txt"
with open(readFile) as f:
   num = f.readlines()
   print(num)

   for x in num[:]:
      x = chr(x)
      print(x)

print(num)给我这个:

['35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,46,100,111,45,34,34,34,34,34,39,45,111,46,46,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,10,\n',

我该如何阅读每一行,然后将它们打印在新行而不是同一行上,因为我有上述几行,但它们全部输出在一行上。此外,什么是使chr()函数正常工作的最佳方法,因为当我尝试打印(x)时出现此错误:

Traceback (most recent call last):
File "C:/Users/Ethan/Desktop/EthanWork/Python/Python Projects/Uni 
 Work/asciiNumToChar/Main.py", line 7, in <module>
   x = chr(x)
TypeError: an integer is required (got type str)

如果有人能帮助我,我将不胜感激,如果您从未直截了当地告诉我答案,我将不胜感激,如果您能指出我自己能够解决问题的方向,我将不胜感激。非常感谢。

谢谢

1 个答案:

答案 0 :(得分:0)

  1. 创建一个list来存储值
  2. split,分别获取值
  3. 将列表中的每个str转换为int
  4. 遍历list以获得char等价物

numbers.txt

35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,46,100,111,45,34,34,34,34,34,39,45,111,46,46,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,10

因此

readFile = "numbers.txt"
numList = []

with open(readFile) as f:
   lines = f.readline()
for line in lines.split(","):
   # print(line)
   numList.append(line)

for x in numList:
    print(chr(int(x)))

输出

#
#
#
#
#
.
.
.
d
o
-
.
.

编辑(简短版)

readFile = "numbers.txt"
numList = []
chr_list = []

with open(readFile) as f:
   lines = f.readline()
for line in lines.split(","):
   numList.append(line)
   chr_list.append(chr(int(line)))

print(numList)
print(chr_list)

输出

['35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '46', '100', '111', '45', '34', '34', '34', '34', '34', '39', '45', '111', '46', '46', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '35', '10\n']
['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '.', 'd', 'o', '-', '"', '"', '"', '"', '"', "'", '-', 'o', '.', '.', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '\n']

编辑2

如果要将每个值映射到其char eqvui (key : val),则可能使用dict方法是有用的:

dict_ = {}
with open(readFile) as f:
   lines = f.readline()
for line in lines.split(","):
   dict_[line] = chr(int(line))

print(dict_)

输出

{'35': '#', '46': '.', '100': 'd', '111': 'o', '45': '-', '34': '"', '39': "'", '10\n': '\n'}