当制表符分隔符来自数据库时,如何编写制表符分隔文件?
我在表达这个问题时遇到了问题,所以我尝试举一个例子:
以下代码可以工作并创建预期的输出:一个分隔文件,其中每列由“真实”选项卡分隔。
CSV.open(@targetfile, "wb", "\t") { |csv|
csv << ["row", "of", "CSV", " }
以下代码不会产生预期的输出。
CSV.open(@targetfile, "wb", @targetdelimiter) { |csv|
csv << ["row", "of", "CSV", "data"] }
在本例中,@targetdelimiter
来自数据库,实际上是字符串 '\t'
(不带引号),可由用户配置。
此代码还生成分隔输出,但我可以看到 '\t'
而不是“真正的”制表符。
考虑到来自数据库的 @targetdelimiter='\t'
,我可以对第二个代码块做什么以获得与第一个代码块相同的结果?
I have a problem really phrasing this question so i try to give an example:
The following code works and creates the expected output: a delimited file where each column is separated by a "real" tab.
CSV.open(@targetfile, "wb", "\t") { |csv|
csv << ["row", "of", "CSV", " }
The following code does not produce the expected out.
CSV.open(@targetfile, "wb", @targetdelimiter) { |csv|
csv << ["row", "of", "CSV", "data"] }
@targetdelimiter
in this case comes from the database and is actually the string '\t'
(without the quotes) which can be configured by the user.
This code produces also a delimited output, but i can see the '\t'
instead of a "real" tab character.
What can I do with the second code block to get the same result as the first codeblock given that the @targetdelimiter='\t'
from the db?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需 gsub 即可完成。
Just gsub it and be done with it.
在第一个示例中用作分隔符时,
\t
会被替换为实际的制表符(ASCII0x09
或Char(9)
) 。在第二个中,它没有被替换,而是被用作文字字符序列\
和t
。如果您没有让用户存储转义序列,而是使用诸如TAB
或NEWLINE
之类的内容,那么您可能会很幸运,然后您可以从数据库中读取并转换它们改为正确的字符(或者您可以将它们从文字转换为正确的字符)。\t
is replaced by an actual tab character (ASCII0x09
, orChar(9)
) when it's used as a delimiter in your first example. In the second, it's not being replaced, and it's being used as the literal character sequence\
andt
. You might have luck if you don't have the users store the escape sequence, and instead use something likeTAB
orNEWLINE
, which you can then read from the database and convert to the proper character instead (or you can just convert them from the literals to the proper character).