How to check if a line is at the beginning of a line despite tabs or spaces?

#!/usr/bin/python
import subprocess as sp
args = ["awk", r'/^word/ { print $1}','anyfile.py' ]
p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE )

How to get a word at the beginning of a line, despite tabs and spaces?

print p.stdout.read()
+4
source share
5 answers

You can just use regex like

import re
re.match(r'^\s*word', line)

Here

  • ^ indicates the beginning of a line

  • \s* means zero or more whitespace characters

  • word is the true word you are looking for.

+2
source

How about using startswithafter use strip-

>>>'\n  \t  \r  asasasas ash'.strip().startswith('asa')
>>>True
+2
source

, awk, :

import subprocess as sp
args = ["awk", r'/^\s*word/ { print $1}','anyfile.py' ]
p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE )
print p.stdout.read()

, Python:

with open("anyfile.py") as f:
    for line in f:
        if line.lstrip().startswith("word"):
            print "found match!"

:

+1

Using only inline string methods is as simple as:

str(p.stdout.read()).split()[0]

This should provide you with the first word in the line.

0
source

It seems like what you really want to do is parse the abstract syntax tree of the python file using the ast module . There are much better ways to do this than using regular expressions. Here is an example:

import ast

class FunctionVisitor(ast.NodeVisitor):

    def __init__(self):
        self.second_arg_names = []

    def visit_FunctionDef(self, func):
        """collect function names and the second argument of functions that 
        have two or more arguments"""
        args = func.args.args
        if len(args) > 1:
            self.second_arg_names.append((func.name, args[1].id))
        self.generic_visit(func)

def find_func_args(filename=__file__):
    """defaults to looking at this file"""
    with open(filename) as f:
        source = f.read()
    tree = ast.parse(source)

    visitor = FunctionVisitor()
    visitor.visit(tree)

    print visitor.second_arg_names
    assert visitor.second_arg_names == [("visit_FunctionDef", "func")]

if __name__ == "__main__":
    find_func_args()    
0
source

Source: https://habr.com/ru/post/1624930/


All Articles