读取RTF文件并解析纯文本

读取RTF文件并解析纯文本

本文介绍了读取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文件并解析纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 07:02