簡體   English   中英

使用python從文件中提取文本

[英]Pulling text from file with python

我有一個要在python代碼中打開的文本文件。 我想搜索該文件並拉出其后跟特定符號的文本。 例如,我的文本文件名File.txt是:

您好,這只是一個虛擬文件,其信​​息完全不包含任何內容,我想在美元符號之間提取信息。 因此,應該將此處之間的所有$都拉出,以便我可以用它做任何我想做的事,其余的將是第二組。

這是我的代碼示例:

class FileExtract(object):
    __init__(self):
        pass

    def extractFile(self):
        file = open(File.txt)
        wholeFile = file.read()
        file.close()
        symCount = wholefile.count("$") 
        count = 0 #Will count the each $ as it finds it
        begin = False #determines which the $ has been found and begin to start copying word
        myWant = [] #will add the portion I want
        for word in wholeFile.split():
            while(count != symCount):
                if word != "$" and begin == False:
                    break
                if word == "$" and begin == False:
                    myWant.append(word)
                    begin = True
                    count = count + 1 #it found one of the total symbols
                    break
                elif word != "$" and begin == True:
                    myWant.append(word)
                    break
                elif word == "$" and begin == True:
                    begin = False
                    break
        print myWant

我想要打印:

"$ in between here should be pulled out so I can do what ever I want to with it" 
"$ and the rest of this will be a second group."

這是我想到的唯一方法(我知道這很可怕,請放心,我只是在學習)。 問題是我的方式是將其放入列表中,我希望它僅將字符串與空格,換行符和所有內容一起打印出來。 我忽略的任何建議或其他內置函數/方法對我有幫助嗎?

s = "Hello, this is just a dummy file that has information with no substance at all and I want to pull the information between the dollar sign symbols. So all of this $ in between here should be pulled out so I can do what ever I want to with it $ and the rest of this will be a second group."

a = s.split("$")[1:]
print a

http://ideone.com/tt9np

當然,定界符不會出現在結果中,但是自己添加它是微不足道的。

好吧,您可以執行wholefile.split('$') ,然后有3個元素列表:第一個$之前是什么,$之間的東西,以及第二個$之后的東西。 (沒有$。)

甚至print '\\n$'.join(wholefile.split('$'))

並且作為最小功能:

def extract_file(filename):
    return '\n$'.join(open(filename).read().split('$'))

這就是flex的目的。 不過,您不需要使用flex在python中執行相同的操作。

firstFlag = False
secondFlag = False
outputFile1 = open('first.txt', 'wb')
outputFile2 = open('second.txt', 'wb')
yourFile = open('thefile.txt', 'rb')
while True:
    char = yourFile.read(1)
    if not char:
        break
    if char == '$'
        if firstFlag:
            secondFlag = True
        firstFlag = True
    if firstFlag and not secondFlag:
        outputFile1.write(data)
    elif secondFlag:
        outputFile2.write(data)

由於這不是本機C代碼,因此不會很快。 我建議您不僅針對方便的工具,還針對學習經驗來學習flex。

flex中的以上代碼:

%option 8bit outfile="scanner.c"
%option nounput nomain noyywrap
%option warn

%x First
%x Second
%%

. { ECHO; }
\$ { BEGIN First; yyout = fopen("first.txt", "wb"); }
<First>\$ { BEGIN Second; fclose(yyout); yyout = fopen("second.txt", "wb");}
<First>. { ECHO; }
<Second>. { ECHO; }

%%

點命令將每個字符發送到yyout,后者開始指向stdout。 編譯此:

flex -Cf scanner.l 
gcc -O -o flexer.exe scanner.c

它將接受來自stdin的輸入。

實際上很簡單。 既不使用split也不將結果存儲在列表中:

def extractFile(self):
    file = open(File.txt)
    wholeFile = file.read()
    file.close()

    pos = wholeFile.find("$")
    while pos > 0:
        pos2 = wholeFile.find("$")

        if pos2 > 0:
            print wholeFile[pos:pos2]
        else:
            print wholeFile[pos:]
        pos = pos2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM