在 Mathematica 中将文件内容提取到字符串中的最佳方法是什么?
我知道这个问题很常见,但谷歌搜索并没有找到 Mathematica 的明确答案,所以我认为在 StackOverflow 上发布这个问题会很有价值。
我一直在使用 Import 来做这件事,但我突然想到这可能效率非常低,因为 Import 是一个如此重量级的函数。
那么问题来了,你能否在以下方面进行改进:
slurp[filename_] := Import[filename, "Text"]
I know this is asked commonly but googling doesn't turn up a definitive answer for Mathematica so I thought it would be valuable to have this on StackOverflow.
I've been doing this with Import but it occurred to me that that might be horribly inefficient, Import being such a heavyweight function.
So the question is, can you improve on the following:
slurp[filename_] := Import[filename, "Text"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了一次导入整个文件,我知道的唯一其他选项是 ReadList。可以将整个文件作为单个字符串返回,如下1:(
注意:\r 和 \n 实际上在输出中解释,但为了便于阅读,我将它们保留在其中。)是删除任何
RecordSeparators
。但是,老实说,我认为这不会为您节省任何东西,并且Import[, "Text"]
更容易编写。说实话,当我的数据格式未包含在Read
和中使用的类型说明符中时,我会使用
,并围绕此操作构建一个自定义函数以加载所有数据。Read[, String]
ReadListFor importing the entire file at once, the only other option that I am aware of is
ReadList
. It can be coaxed to returning the entire file as a single string as follows1:(Note: \r and \n are actually interpreted in the output, but I left them in for readability.) The key is to remove any
RecordSeparators
. But, I honestly don't think this saves you anything, andImport[ <file>, "Text"]
is easier to write. Truthfully, I useRead[ <file>, String]
when I have data in a format that isn't covered by the type specifiers used inRead
andReadList
, and build a custom function around this operation to load in all of the data.