简体   繁体   English

将多个字符串转换为ASCII

[英]Conversion of Multiple Strings To ASCII

This seems fairly trivial but I can't seem to work it out 这似乎微不足道,但我似乎无法解决

I have a text file with the contents: 我有一个包含内容的文本文件:

B>F B> F

I am reading this with the code below, stripping the '>' and trying to convert the strings into their corresponding ASCII value, minus 65 to give me a value that will correspond to another list index 我正在用下面的代码阅读此内容,剥离“>”并尝试将字符串转换为相应的ASCII值减65,以便给我一个将与另一个列表索引相对应的值

def readRoute():
    routeFile = open('route.txt', 'r')
    for line in routeFile.readlines():
        route = line.strip('\n' '\r')
        route = line.split('>')
        #startNode, endNode = route
        startNode = ord(route[0])-65
        endNode = ord(route[1])-65

    # Debug  (this comment was for my use to explain below the print values)
    print 'Route Entered:'
    print line
    print startNode, ',', endNode, '\n'
    return[startNode, endNode]

However I am having slight trouble doing the conversion nicely, because the text file only contains one line at the moment but ideally I need it to be able to support more than one line and run an amount of code for each line. 但是,我很难很好地进行转换,因为文本文件目前仅包含一行,但理想情况下,我需要它能够支持多行并为每一行运行大量代码。

For example it could contain: 例如,它可能包含:

B>F
A>D 
C>F 
E>D

So I would want to run the same code outside this function 4 times with the different inputs 所以我想用不同的输入在此函数外运行相同的代码4次

Anyone able to give me a hand 任何人都可以帮我的忙

Edit: 编辑:

Not sure I made my issue that clear, sorry 不确定我是否明确指出了问题,对不起

What I need it do it parse the text file (possibly containing one line or multiple lines like above. I am able to do it for one line with the lines 我需要做的是解析文本文件(可能包含如上所述的一行或多行。我可以用一行完成一行

startNode = ord(route[0])-65
endNode = ord(route[1])-65

But I get errors when trying to do more than one line because the ord() is expecting different inputs If I have (below) in the route.txt 但是尝试执行多行操作时出现错误,因为ord()预期输入不同,如果route.txt中有(以下)

B>F
A>D

This is the error it gives me: 这是它给我的错误:

line 43, in readRoute  endNode = ord(route[1])-65
TypeError: ord() expected a character, but string of length 2 found

My code above should read the route.txt file and see that B>F is the first route, strip the '>' - convert the B & F to ASCII, so 66 & 70 respectively then minus 65 from both to give 1 & 5 (in this example) The 1 & 5 are corresponding indexes for another "array" (list of lists) to do computations and other things on Once the other code has completed it can then go to the next line in route.txt which could be A>D and perform the above again 我上面的代码应该读取route.txt文件,并看到B> F是第一条路由,去掉'>'-将B&F转换为ASCII,所以分别将66和70分别减去65和70分别得到1和5 (在此示例中)1和5是另一个“数组”(列表列表)的对应索引,以进行计算和其他操作。其他代码完成后,便可以转到route.txt中的下一行,该行可能是A> D并再次执行以上操作

Perhaps this will work for you. 也许这对您有用。 I turned the fileread into a generator so you can do as you please with the parsed results in the for-i loop. 我将fileread转换为一个生成器,因此您可以根据需要在for-i循环中执行解析结果。

def readRoute(file_name): 
    with open(file_name, 'r') as r:
        for line in r:
            yield (ord(line[0])-65, ord(line[2])-65)

filename = 'route.txt'

for startnode, endnode in readRoute(filename):
    print startnode, endnode

If you can't change readRoute, change the contents of the file before each call. 如果您无法更改readRoute,请在每次调用之前更改文件的内容。 Better yet, make readRoute take the filename as a parameter (default it to 'route.txt' to preserve the current behavior) so you can have it process other files. 更好的是,使readRoute将文件名作为参数(默认为“ route.txt”以保留当前行为),以便您可以处理其他文件。

What about something like this? 那这样的东西呢? It takes the routes defined in your file and turns them into path objects with start and end member variables. 它采用文件中定义的路由,并将其转换为带有startend成员变量的路径对象。 As an added bonus PathManager.readFile() allows you to load multiple route files without overwriting the existing paths. 另外, PathManager.readFile()允许您加载多个路由文件而不会覆盖现有路径。

import re

class Path:
  def __init__(self, start, end):
     self.start = ord(start) - 65  # Scale the values as desired
     self.end = ord(end) - 65  # Scale the values as desired

class PathManager:
  def __init__(self):
    self.expr = re.compile("^([A-Za-z])[>]([A-Za-z])$") # looks for string "C>C" 
                                                        # where C is a char
    self.paths = []

  def do_logic_routine(self, start, end):
    # Do custom logic here that will execute before the next line is read
    # Return True for 'continue reading' or False to stop parsing file
    return True

  def readFile(self, path):
    file = open(path,"r")
    for line in file:
      item = self.expr.match(line.strip()) # strip whitespaces before parsing
      if item:
        '''
        item.group(0) is *not* used here; it matches the whole expression
        item.group(1) matches the first parenthesis in the regular expression
        item.group(2) matches the second
        '''
        self.paths.append(Path(item.group(1), item.group(2)))
        if not do_logic_routine(self.paths[-1].start, self.paths[-1].end):
          break

# Running the example
MyManager = PathManager()
MyManager.readFile('route.txt')
for path in MyManager.paths:
  print "Start: %s End: %s" % (path.start, path.end)

Output is: 输出为:

Start: 1 End: 5
Start: 0 End: 3
Start: 2 End: 5
Start: 4 End: 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM