如何解决删除以特定字符串开头的每个单词
我正在尝试删除文本文件中以某个字符串开头的每个单词。我被困在如何写输出文件上。
输入文件:
Lorem ipsum applePEAR
dolor appleBANANA sit
appleORANGE amet,consectetur
所需的输出文件:
Lorem ipsum
dolor sit
amet,consectetur
到目前为止我的方法:
with open(infile) as fin,open(outfile,"w+") as fout:
for line in fin:
ls = line.split()
for word in ls():
if word.startswith("apple"):
line.replace(word,"")
fout.write(line)
我认为这种方法的问题在于替换行拆分列表中的单词,而不是替换行本身。
检查Stackoverflow,我发现此问题类似于:using Python for deleting a specific line in a file,除了“ nickname_to_delete”是一个以字符串开头的单词。
解决方法
我已尽可能少地更新您的代码:
with open(infile) as fin,open(outfile,"w+") as fout:
for line in fin:
ls = line.split(" ")
newline = []
for word in ls: # Don't call() the list
if not word.startswith("apple"):
newline.append(word) # Append all words that don't start with apple.
fout.write(" ".join(newline)) # Remake new line
请记住,用正则表达式替换会更好,并且可以处理“ newword,appleshake”:
import re
with open(infile) as fin,"w+") as fout:
for line in fin:
fout.write(re.sub(r"\bapple\w+","",line))
\w
仍然会标点符号,但是您需要选择处理方式。
有一些问题。
- 您正在呼叫
ls()
-应该只是ls
- 调用
line.replace()
(除了错字)不会修改line
的内容-只是返回一个新字符串,然后您将其丢弃 - 原则上存在这样的风险:通过以这种方式进行替换,您还将无意中删除其他单词的一部分-在“我喜欢菠萝和苹果”行中,“菠萝”中的“苹果”也将获得已删除(“我喜欢松木和”)。
这里是一种替代方法(注意限制:单词之间的空白量不保留)。
with open(infile) as fin,"w+") as fout:
for line in fin:
ls = line.split()
words = [word for word in ls if not word.startswith('apple')]
line_out = ' '.join(words)
fout.write(line_out + '\n')
,
也可以使用过滤器
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public Namedata[] namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
HttpClient _client = new HttpClient();
string username = "myuser";
string password = "myuserpass";
var byteArray = System.Text.Encoding.ASCII.GetBytes($"{username}:{password}");
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",Convert.ToBase64String(byteArray));
dynamic content = new ExpandoObject();
content.name = Name.Text;
content.id = 1;
var json = Newtonsoft.Json.JsonConvert.SerializeObject(content);
var data = new StringContent(json,System.Text.Encoding.UTF8,"application/json");
var response = _client.PostAsync("http://myservice/Service4.svc/s_name",data).Result;
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Example>(response.Content.ReadAsStringAsync().Result);
ultragridiew1.DataSource = data.s_name.namedatas;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。