使用Applscripts解析文本

时间:2016-09-20 01:22:07

标签: applescript

我可以使用一些帮助编写Applescript来解析.txt文件中的一些文本并输出到单独的.txt文件。我需要一个脚本来1)识别一个部分(由“»=”除名),2)识别一个部分中是否存在一组特定的字符,“[*]”,3)打印包含所有包含特定部分的部分标题字符集,4)重复到文件结尾。基本上,这些是带有操作项的注释,我想提取包含开放操作项的注释。

notes.txt中的输入文本结构如下:

»===============================

<Date> 2016-09-19
<Topic> The topic of the day
<Attendees> Mario, Luigi

»1) Where to go from here
- Someone said this
    [*] Mario: schedule this meeting
- And who wants to do that other thing?

»2) And on to the next thing

»3) So on and so forth [*] Luigi can order the pizza
»===============================

<Date> 2016-09-18
<Topic> The topic of the yesterday
<Attendees> Zelda, Wario, Snoop Dog

»1) Where we went from there
- Who said this
    [x] Mario: scheduled this meeting yesterday
- And who wants to do that other thing?

»2) And on to the next thing again

»3) So on and so forth * Luigi can order the sausages
»===============================

输出文本到actionItems.txt应该如下:

»===============================

<Date> 2016-09-19
<Topic> The topic of the day
<Attendees> Mario, Luigi

»1) Where to go from here
- Someone said this
    [*] Mario: schedule this meeting
- And who wants to do that other thing?

»3) So on and so forth [*] Luigi can order the pizza
»===============================

也许我可以得到一点帮助?谢谢!

1 个答案:

答案 0 :(得分:0)

使用Applescript读取和编写文本文件非常简单:

阅读:

set myFile to choose file "Select your txt file" -- ask user to select txt file
set myText to (read myFile) as string -- content the text file is in variable myText

将文本变量newText的内容写入桌面上的文件'action items.txt':

set newFile to ((path to desktop) as string) & "actionItems.txt"
try
    open for access file newFile with write permission
    write (newText & return) to file newFile starting at eof
    close access file newFile
on error
try
    close access file newFile
end try
end try

在两者之间,您必须使用功能强大的“项目文本分隔符”拆分文本。您必须首先定义分隔符,如:

set AppleScript's text item delimiters to {"»=", "¬ª="}

(在我的测试中,我发现你的“»=”应该是,实际上设为“¬ª=”!!)

然后,您可以通过重复循环访问每个文本项(两个分隔符之间的文本部分):

set AppleScript's text item delimiters to {"»=", "¬ª="}
set myNotes to text items of myText
set newText to ""
repeat with I from 1 to (count of myNotes) --loop through each item
    -- do what ever you need with 'item I of myNotes'
    set Newtext to "this is my test" -- assign new text to be written
end repeat

您需要在循环中调整您的测试:例如,如果您的文字以空格开头,那么,第1项将不是您预期的标题,而是空格!

最后一件事:要测试文本变量是否包含某些内容,请使用“包含”字:

Set A to "This is my text sample"
if A contains "is my" then 
    -- A contains 'is my'
else
    -- A do not contains 'is my'
end if
祝你好运!