簡體   English   中英

如何在TensorFlow的字符串張量上執行正則表達式操作?

[英]How to perform regex operations on a string tensor on TensorFlow?

如何在字符串張量上執行正則表達式操作? 通常,我只會使用python字符串,但是當使用Tensorflow Serving時,我需要輸入為字符串張量。 因此,我創建了一個字符串占位符,然后將另一層注入到圖形中,並在其中插入占位符,並准備將其傳遞給模型。

我已經看過使用py_func但是仍然無法對類似字節的對象執行模式操作。

有沒有辦法在張量上執行這些操作? 我無法在占位符上執行eval(),因為僅當saveModel加載並運行時才提供數據。

我一直用於測試的代碼:

def remove_urls(vTEXT):
    vTEXT = re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b', 'url', vTEXT, flags=re.MULTILINE)
    return(vTEXT)


input_string_ph = tf.constant("This is string https:www.someurl.com")

input_string_lower = tf.py_func(lambda x: x.lower(), [input_string_ph], tf.string, stateful=False)
# input_string_no_url = tf.py_func(lambda x: remove_urls(x), [input_string_lower], tf.string, stateful=False)
sess = tf.InteractiveSession()
print (input_string_no_url.eval())

似乎String張量返回一個字節值而不是py_func的字符串值,因此在remove_urls ,您應該使用decode

def remove_urls(vTEXT):
    vTEXT = vTEXT.decode('utf-8')
    vTEXT = re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b', 'url', vTEXT, flags=re.MULTILINE)
    return(vTEXT)

例如,您可以使用tf.regex_replace()運算符從字符串中刪除子字符串並檢查是否成功:

import tensorflow as tf

str = tf.constant("your string")
sub_str = tf.constant("string")

def not_contains(str1, str2):
    cut1 = tf.regex_replace(str1, str2, "")
    split1 = tf.string_split([cut1], "")
    split2 = tf.string_split([str1], "")
    size1 = tf.size(split1)
    size2 = tf.size(split2)
    return tf.equal(size1, size2)

is_not_in = not_contains(str, sub_str)

sess = tf.Session()
sess.run(is_not_in) # False

暫無
暫無

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

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