簡體   English   中英

字符之間的Python Grabbing String

[英]Python Grabbing String in between characters

如果我有一個類似/ Hello的字符串, 您好 /,我應該如何抓取這一行並使用python腳本將其刪除。

import sys
import re

i_file = sys.argv[1];

def stripwhite(text):
    lst = text.split('"')
    for i, item in enumerate(lst):
        if not i % 2:
            lst[i] = re.sub("\s+", "", item)
    return '"'.join(lst)

with open(i_file) as i_file_comment_strip:

        i_files_names = i_file_comment_strip.readlines()

        for line in i_files_names:
                with open(line, "w") as i_file_data:
                        i_file_comment = i_file_data.readlines();
                        for line in i_file_comment:
                                i_file_comment_data = i_file_comment.strip()

在i_file_comment中,我具有來自i_file_data的行,而i_file_comment包含具有“ / ... /”格式的行。 我會使用for循環遍歷該行中的每個字符,並將其中的每個字符替換為“”嗎?

如果要刪除/ Hello,您/可以如何使用regex:

import re
x = 'some text /Hello how are you/ some more text'
print (re.sub(r'/.*/','', x))

輸出:

some text  some more text

如果您知道行中出現了固定的字符串,則只需

for line in i_file_comment:
    line = line.replace('/Hello how are you/', '')

但是,如果您有多次出現以/分隔的字符串(即/ foo /,/ bar /),我認為使用簡單的正則表達式就足夠了:

>>> import re
>>> regex = re.compile(r'\/[\w\s]+\/')
>>> s = """
... Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
... /Hello how are you/ ++ tempor incididunt ut labore et dolore magna aliqua.
... /Hello world/ -- ullamco laboris nisi ut aliquip ex ea commodo
... """
>>> print re.sub(regex, '', s)  # find substrings matching the regex, replace them with '' on string s

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
 ++ tempor incididunt ut labore et dolore magna aliqua.
 -- ullamco laboris nisi ut aliquip ex ea commodo

>>>

只需將正則表達式調整為您需要擺脫的:)

暫無
暫無

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

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