读取RTF文件并解析纯文本

编程入门 行业动态 更新时间:2024-10-11 23:25:44
本文介绍了读取RTF文件并解析纯文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我这样做是为了使用NSOpenPanel获取文件的内容,但是我从选择的.rtf文件中返回了很多奇怪的东西.

I am doing this to get the content of a file using NSOpenPanel, but I am getting a lot of weird stuff returned from the .rtf file I select.

我的面板代码:

var panel: NSOpenPanel = NSOpenPanel() var fileTypesArray: NSArray = ["txt", "rtf", "nil"] panel.canChooseFiles = true panel.allowedFileTypes = fileTypesArray as [AnyObject] panel.allowsMultipleSelection = false if panel.runModal() == NSModalResponseOK { var url = panel.URL!.path println(url) let path = url let expandedPath = path!.stringByExpandingTildeInPath let data: NSData? = NSData(contentsOfFile: expandedPath) if let fileData = data { let content = NSString(data: fileData, encoding:NSUTF8StringEncoding) as! String println(content) } }

.rtf文档的内容是"Testing 123"(测试123)

The contents of my .rtf document is "Testing 123"

这是要打印到控制台上的内容:

This is what is being printed to the console:

{\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural \f0\fs24 \cf0 Testing 123\ }

有什么办法可以使我仅从文件中获取文本,还有其他正在打印的东西吗?

Is there any way I can get just the text from the file, and what is all the other stuff that is being printed?

推荐答案

其他内容"是实际的RTF数据.

That "other stuff" is the actual RTF data.

我建议使用NSAttributedString初始化程序 NSAttributedString(path:documentAttributes:) ,它将读取并处理RTF数据.然后,您可以使用attributedString.string访问纯文本.

I would recommend using the NSAttributedString initializer NSAttributedString(path:documentAttributes:), which will read in and process the RTF data. Then you can access the plain text by using attributedString.string.

您的情况应该是

if let content = NSAttributedString(path: expandedPath, documentAttributes: nil) { // do something with content or content.string }

更多推荐

读取RTF文件并解析纯文本

本文发布于:2023-10-12 04:35:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483729.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   文件   RTF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!