【问题标题】:PYTHON : How to find block comments string in PythonPYTHON:如何在 Python 中查找块注释字符串
【发布时间】:2013-08-06 11:52:57
【问题描述】:

我想在 python 中解析块 cmets。我为了做到这一点,我需要在 .py 文件中找到 cmets 部分。

例如,我的 sample.py 包含

'''
This is sample file for testing
This is sample file for development
'''
import os
from os import path
def somefun():
    return

我想解析我在 sampleparsing.py 中尝试执行的 cmets 部分

tempfile = open('sample.py', 'r')
for line in tempfile: 
    if(line.find(''''') != -1):
        dosomeoperation()
        break

Since if(line.find(''''') != -1): 假设下面的剩余行已注释如何替换此字符串以查找 cmets?

我尝试在两者之间保留“\”(转义字符),但找不到解决此问题的方法。

在sampleparsing.py中解析后需要以下两行:

This is sample file for testing
This is sample file for development

【问题讨论】:

  • 你知道 ''' 不是块 cmets 对吗?我的意思是有时可以这样使用,但是...
  • 为什么不import sample; print sample.__doc__
  • @JoranBeasley,Python 的创建者 Guido Von Rossum,赞成使用多行字符串作为多行 cmets。见这里:twitter.com/gvanrossum/status/112670605505077248
  • @houdini:当然,多行字符串可以合法地用作评论。但是,它也可以用作多行字符串。这就是乔兰所说的:并不总是评论。
  • @rici 我不想让阅读本文的程序员认为这是错误的做法。看起来 Joran 是在暗示这样做可能不“合适”。

标签: python string parsing python-2.7


【解决方案1】:

试试这个

tempfile = open('sample.py', 'r')
lines = tempfile.readlines()
comments = lines.split( "'''" )
tempfile.close()

假设文件以注释块开头,注释块现在应该是奇数索引,1、3、5...

【讨论】:

    【解决方案2】:

    改用"'''" 作为您的字符串。现在 Python 认为你还在写一个字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-29
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      相关资源
      最近更新 更多