2013-04-28 56 views
1

使用python,我想“教育”纯文本输入的引号并将它们转换为上下文语法。这里是(递归)例如:解析文本以替换引号和嵌套引号

原文:

Using python, I would like "educate" quotes of 
a plain text input and turn them into the Context syntax. 
Here is a (recursive) example: 

输出:

Using python, I would like \quotation{educate} quotes of 
a plain text input and turn them into the Context syntax. 
Here is a (recursive) example: 

我想它来处理嵌套的报价,以及:

原文:

Original text: "Using python, I would like 'educate' quotes of 
a plain text input and turn them into the Context syntax. 
Here is a (recursive) example:" 

输出:

Original text: \quotation {Using python, I would like \quotation{educate} quotes of 
a plain text input and turn them into the Context syntax. 
Here is a (recursive) example:} 

当然,我应该照顾的边缘情况,例如:

She said "It looks like we are back in the '90s" 

上下文规格报价是在这里:

http://wiki.contextgarden.net/Nested_quotations#Nested_quotations_in_MkIV

是什么对这种情况最敏感的方法?非常感谢你!

回答

3

这一个嵌套引号的作品,虽然它不处理你的优势的情况下

def quote(string): 
    text = '' 
    stack = [] 
    for token in iter_tokes(string): 
     if is_quote(token): 
      if stack and stack[-1] == token: # closing 
       text += '}' 
       stack.pop() 
      else: # opening 
       text += '\\quotation{' 
       stack.append(token) 
     else: 
      text += token 
    return text 

def iter_tokes(string): 
    i = find_quote(string) 
    if i is None: 
     yield string 
    else: 
     if i > 0: 
      yield string[:i] 
     yield string[i] 
     for q in iter_tokes(string[i+1:]): 
      yield q 

def find_quote(string): 
    for i, char in enumerate(string): 
     if is_quote(char): 
      return i 
    return None 

def is_quote(char): 
    return char in '\'\"' 

def main(): 
    quoted = None 
    with open('input.txt') as fh: 
     quoted = quote(fh.read()) 
    print quoted 

main() 
+0

谢谢,这是一个非常好的模板。我需要收集一些边缘案例以用真实情况进行测试,并相应地进行调整。 – Alex 2013-04-28 16:01:12

0

如果你确定原文在正确的地方有空间,你可以简单地使用正则表达式:

regexp = re.compile('(?P<opening>(?:^|(?<=\\s))\'(?!\\d0s)|(?<=\\s)")|["\'](?=\\s|$)') 

def repl(match): 
    if match.group('opening'): 
     return '\\quotation{' 
    else: 
     return '}' 

result = re.sub(regexp, repl, s) 
+0

感谢。我将无法控制输入,所以我更喜欢更通用的解决方案。 – Alex 2013-04-28 15:57:06