“file”命令产生“ASCII 文本,没有行终止符”,除非我首先在 vim 中编辑文件

cor*_*cor 6 linux terminal vim python ascii

我正在试验一种我不知道如何解决的奇怪行为。我将解释这个场景:

  • 从 Python 脚本中,我从parse 上托管的简单应用程序中获取了 json 。
  • 一旦我得到文本,我就会从中得到一个句子并将其保存到本地“txt”文件中,将其另存为 iso-8859-15。
  • 最后我将它发送到一个文本到语音处理器,它期望在 ISO-8859-15 上接收它

奇怪的是,一旦python脚本运行,如果我运行

file my_file.txt
Run Code Online (Sandbox Code Playgroud)

输出是:

my_file.txt: ASCII text, with no line terminators
Run Code Online (Sandbox Code Playgroud)

但是如果我my_file.txt用vim打开,然后把句子的最后一个“点”去掉,再写一遍,然后保存文件:如果我再做:

file my_file.txt
Run Code Online (Sandbox Code Playgroud)

现在输出是:

my_file.txt: ASCII text
Run Code Online (Sandbox Code Playgroud)

解决了语音合成器处理时的一些问题。那么,如何在不做 vim 的情况下自动强制这种行为?我也做了很多尝试iconv,但都没有成功。

任何帮助将非常感激

编辑:

i@raspberrypi ~/main $ hexdump -C my_file.txt

00000000  73 61 6d 70 6c 65 20 61  6e 73 77 65 72 2e 2e     |sample answer..|
0000000f

pi@raspberrypi ~/main $ file my_file.txt
my_file.txt: ASCII text, with no line terminators
pi@raspberrypi ~/main $ vim my_file.txt
pi@raspberrypi ~/main $ file my_file.txt
my_file.txt: ASCII text
pi@raspberrypi ~/main $ hexdump -C my_file.txt

00000000  73 61 6d 70 6c 65 20 61  6e 73 77 65 72 2e 2e 0a  |sample answer...|
00000010
Run Code Online (Sandbox Code Playgroud)

示例文件

蟒蛇代码:

import json,httplib
from random import randint
import codecs

connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('GET', '/1/classes/XXXX', '', {
       "X-Parse-Application-Id": "xxxx",
       "X-Parse-REST-API-Key": "xxxx"
     })
result = json.loads(connection.getresponse().read())

pos = randint(0,len(result['results'])-1)
sentence = result['results'][pos]['sentence'].encode('iso-8859-15')
response = result['results'][pos]['response'].encode('iso-8859-15')

text_file = codecs.open("sentence.txt", "w","ISO-8859-15")
text_file.write("%s" % sentence)
text_file.close()

text_file = open("response.txt","w")
text_file.write("%s" % response)
text_file.close()
Run Code Online (Sandbox Code Playgroud)

Sco*_*son 6

该标准/bin/echo可用于为您将该换行符添加到文件末尾:

$ echo -n 'ssss'>test
$ file test
test: ASCII text, with no line terminators
$ hexdump -C test 
00000000  73 73 73 73                                       |ssss|
00000004
$ echo >> test
$ file test
test: ASCII text
$ hexdump -C test 
00000000  73 73 73 73 0a                                    |ssss.|
00000005
$ 
Run Code Online (Sandbox Code Playgroud)

另一种选择是将它添加到您的 Python 代码中:

$ echo -n 'ssss'>test
$ file test
test: ASCII text, with no line terminators
$ hexdump -C test 
00000000  73 73 73 73                                       |ssss|
00000004
$ echo >> test
$ file test
test: ASCII text
$ hexdump -C test 
00000000  73 73 73 73 0a                                    |ssss.|
00000005
$ 
Run Code Online (Sandbox Code Playgroud)