【问题标题】:Remove quotation mark from .txt从 .txt 中删除引号
【发布时间】:2022-01-17 18:42:20
【问题描述】:

我有一个具有以下行类型的 txt 文件:

"Hello I'm in Tensorflow"
"My name is foo"
'Mr "alias" is running'
...

因此可以看出,每行只有一个字符串。当我尝试创建tf.data.Dataset 时,输出如下所示:

conver = TextLineDataset('path_to.txt')
for utter in conver:
    print(utter)
   break
# tf.Tensor(b'"Hello I'm in Tensorflow"', shape=(), dtype=string)

如果您注意到,引号" 仍然出现在字符串的开头和结尾(加上由张量' 定义的)。我想要的输出是:

# tf.Tensor(b'Hello I'm in Tensorflow', shape=(), dtype=string)

即不带引号。 提前谢谢你

【问题讨论】:

  • 遍历行和strip(b'"')…?!
  • 你好@deceze我认为strip是用于空格的,我只想从每行的开头和结尾删除"
  • @deceze 哦,我以为你说的是​​tf.strings.strip。问题是通过使用pd.read_csv() 打开文件,它可以正确读取,没有引号
  • 因为pd.read_csv 将格式解释为CSV,其中" 充当分隔符,而不是值本身的一部分。

标签: python tensorflow tensorflow2.0 tensorflow-datasets


【解决方案1】:

你可以使用tf.strings.regex_replace:

import tensorflow as tf
conver = tf.data.TextLineDataset('/content/text.txt')

def remove_quotes(text):
  text = tf.strings.regex_replace(text, '\"', '')
  text = tf.strings.regex_replace(text, '\'', '')
  return text

conver = conver.map(remove_quotes)
for s in conver:
  print(s)
tf.Tensor(b'Hello Im in Tensorflow', shape=(), dtype=string)
tf.Tensor(b'My name is foo', shape=(), dtype=string)
tf.Tensor(b'Mr alias is running', shape=(), dtype=string)

或者,如果您只想删除前导引号和尾引号,请尝试以下操作:

text = tf.strings.regex_replace(text, '^[\"\']*|[\"\']*$', '')

【讨论】:

  • 我知道我不能发布这种类型的消息,但感谢您在这周内回答了我的大部分问题,您对我的帮助非常大,谢谢!
【解决方案2】:

eval() 函数应该这样做。

for utter in conver:
    print(eval(utter))
   break

或者你可以简单地使用replace -

for utter in conver:
    print(utter.replace('"',''))
   break

【讨论】:

  • 您应该非常非常确定所有可能的值,然后再通过eval!
  • 感谢回答!但是其中有一些字符串的值为",所以我只需要删除第一个和最后一个值
【解决方案3】:

如果要在字符串中保留不在字符串末尾或开头的引号 -

for utter in conver:
    print(''.join([utter[i] if not (utter[i] == '"' and (i==0 or i==len(utter)-1)) else '' for i in range(len(utter))]))
  break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-07
    • 2021-04-24
    • 2011-01-08
    • 2014-06-16
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多