我正在制作一种编程语言,我目前面临的一个问题是如何将包含每行文本文件的列表拆分成更多的项。
例如:
! This is a single line comment
!!!
This line should be ignored
and this one as well
!!!
message_print.Hello World ; message_print.This is multiple line!
应该呈现为
['! This is a single line comment', '', '!!!', 'This line should be ignored', 'and this one as well', '!!!', '', 'message_print.Hello World', 'message_print.This is multiple line!'
我已经试过了
content = [l.split(',') for l in ','.join(content).split(' ; ')]
和
content = [x.split(" ; ") for x in content if x.strip()]
但是当我的脚本调用上述类型的2时,会创建一个列表列表,这不是我想要的。
另外,替换
content=[x.split(“;”)如果x.strip(),则内容中的x为x
具有
content = (x.split(" ; ") for x in content if x.strip())
只会导致运行时错误
另外,下面是负责呈现代码的代码
from sys import argv as args
from sys import exit as quit
import syntax
try:
args[1]
except IndexError:
print("ERROR: No ROS Code file provided in execution arguments")
print("Ensure the execution code looks something like this: python run-file.py test.ros")
with open(args[1]) as f:
ignoreline = False
content = f.readlines()
content = [x.strip() for x in content if x.strip()]
# The code to split a list into more list items goes here
for value in enumerate(content):
if not(value[1].startswith('!')) and ignoreline == False:
firstpart = value[1].split(".")[0]
lenoffirstpart = len(value[1].split(".")[0])
afterpart = str(value[1][lenoffirstpart + 1:])
apwithcomma = afterpart.replace(".", "', '")
preprint = str(firstpart + "(" + apwithcomma + ")")
printtext = preprint.replace("(", "('")
lastprinttext = printtext.replace(")", "')")
try:
exec(str("syntax." + lastprinttext))
except Exception as e:
template = "ERROR: An error of type {0} occured while running line {1} because {2}"
message = template.format(
type(e).__name__, str(value[0] + 1), str(e.args[0]))
print(message)
quit(1)
elif value[1].startswith('!!!'):
ignoreline = not(ignoreline)
quit(0)
我运行的执行脚本的命令如下
@echo off
python run-file.py test.ros
pause
以及
test.ros
文件在这里
啊!这是单行注释
啊!!!
应该忽略这一行
还有这个
啊!!!
message_print.hello world;message_print.这是多行!
如果要查看所有相关文件,请查看
Github Commit
(只有其中一些与解决这个问题有关)