匹配一个字符串的开头和结尾_我如何构建一个应用程序来展示精彩小说的开头和结尾

匹配一个字符串的开头和结尾

I know sentences. In my decade as a print journalist, I’ve written hundreds of articles for dozens of publications. I’ve dished out more sentences than Judge Judy. But I didn’t study writing or journalism, at least not formally.

我知道句子。 在担任印刷记者的十年中,我为数十种出版物撰写了数百篇文章。 我比朱迪法官多了几句。 但是我没有学习写作或新闻学,至少没有正式学习过。

My degree is in electrical engineering. I learned to write by studying, and imitating, the sentences of professional writers. And writers are at their best, generally, in their first and last sentences.

我的学位是电气工程。 我通过学习和模仿专业作家的句子来学习写作。 通常,作家的第一句和最后一句都是最好的。

“The most important sentence in any article is the first one.
“任何一篇文章中最重要的一句话是第一句话。
You should give as much thought to choosing your last sentence as you did your first.”
在选择最后一句话时,您应该多加考虑。

On Writing Well, William Zinsser

在《写得好》中 ,威廉·辛塞尔

One way to get a feel for how to construct good sentences is to type out the prose of writers you admire while reading it aloud. Hunter S. Thompson copied entire novels, punching The Great Gatsby and A Farewell to Arms into his typewriter to get Fitzgerald and Hemingway into his fingers.

感受如何构筑好的句子的一种方法是在朗读时打出您欣赏的作家的散文。 亨特·汤普森(Hunter S. Thompson) 复制了整本小说 ,将《大盖茨比》《永别了,武器》打入了打字机,以使费兹杰拉德和海明威进入他的手指。

I haven’t done anything that extreme, but I have, for many years, typed out the first and last sentences of every book I read, which has resulted in an ever-growing list and, I hope, improvements to my own writing.

我没有做过那么极端的事情,但是多年以来,我一直在打字,以阅读的每本书的开头和结尾是句子,这导致了清单不断增加 ,我希望可以改善自己的写作。

But I can read only so many books and log only so many sentences in the few hours I have each day between earning $’s and catching Z’s. Kids to raise, rugs to vacuum, Stranger Things to binge — you know, life.

但是在每天赚取$到碰到Z的几天之间,我每天只能读那么多书,只记录那么多句子。 孩子们要养育,地毯要吸尘, 陌生人要暴饮暴食-你知道,生活。

Wouldn’t it be great, I’ve often thought, if there were a place online where anyone could contribute the first and last sentences of the books they were reading. We could, together, build a treasure trove of sentences. It would be a great resource for people who, like me, enjoy learning by imitation.

我经常想,如果有一个在线的地方,任何人都可以贡献他们正在阅读的书的开头和结尾的句子,那不是很好吗? 我们可以一起建立句子的宝库。 对于像我一样喜欢模仿学习的人们来说,这将是一个巨大的资源。

Well, it just so happens that my latest obsession is learning to program in JavaScript. So I have begun, with my limited knowledge, to make that place myself, using the JavaScript frameworks MongoDB, Express, Angular 2, and Node.js — known, collectively, as the MEAN stack. I’ve called this (very simple) web application First and Last.

好吧,碰巧的是,我最近的痴迷是学习用JavaScript编程。 因此,以我有限的知识,我开始使用JavaScript框架MongoDB,Express,Angular 2和Node.js(统称为MEAN堆栈)将自己放置在该位置。 我把这个(非常简单的)Web应用程序称为First和Last

“Some appreciate fine art; others appreciate fine wines. I appreciate fine sentences.”
“有些人欣赏美术; 其他人则喜欢上等葡萄酒。 我很欣赏好的句子。”
— How to Write a Sentence and How to Read One, Stanley Fish
—如何写一句句子,以及如何阅读一句话,史丹利·菲什(Stanley Fish)

The rest of this post will alternate between sections describing more of my thoughts on how to write better sentences and sections explaining some of what I learned about programming while working on First and Last.

本文的其余部分将在各节之间交替进行介绍,这些节描述了我对如何编写更好的句子的更多想法,而各节则解释了我在进行“第一”和“最后”时所学到的编程知识。

If you are interested only in writing, feel free to skip the sections on programming. If are interest only in programming, you can scroll past the parts on writing. If you are interested only in ironing your underpants while skydiving or mountain climbing, please go here instead.

如果您只对写作感兴趣,请随时跳过编程部分。 如果仅对编程感兴趣,则可以滚动书写。 如果您只想在跳伞或爬山时熨烫内裤,请改在这里

阅读一切 (Read everything)

If you aspire to be a literary star — the next Jonathan Franzen or Zadie Smith — then stick to reading highbrow literature. Learn from the masters. But most people who want to improve their writing have more modest goals.

如果您渴望成为文学明星-下一个乔纳森·弗朗岑(Jonathan Franzen)或扎迪·史密斯(Zadie Smith),那么请坚持阅读高调的文学作品。 向大师学习。 但是大多数想提高自己的写作水平的人的目标都比较低。

“Every book you pick up has its own lesson or lessons, and quite often the bad books have more to teach than the good ones.”
“您拿起的每一本书都有自己的一堂课,而且坏书常常比好书教书多。”
— On Writing, Stephen King
—关于写作,斯蒂芬·金(Stephen King)

Perhaps you want to start a blog or write a Medium post for Free Code Camp. Maybe you want to impress your boss by writing better reports.

也许您想为Free Code Camp创建博客或撰写中型帖子 。 也许您想通过撰写更好的报告来打动您的老板。

In my city — Ottawa, Ontario — about 150,000 people work for the Canadian federal government. Thousands more are employed by the city. The most frequently produced pieces of writing here, I reckon, are government documents: memos, briefing notes, regulations, media releases, policies, public advisories, guidelines, and so on.

在我的城市(安大略省渥太华),约有15万人为加拿大联邦政府工作。 这个城市雇用了成千上万的人。 我认为,这里最常用的文字是政府文件:备忘录,简报,法规,媒体发布,政策,公共咨询,指南等。

Are most of these documents written well? Ah, let’s just say there’s room for improvement. Lots of room. Canada-size room.

这些文件大部分写得好吗? 啊,我们只能说还有改进余地 。 很多房间。 加拿大大小的房间。

People who simply want to write more clearly and concisely may find greater benefit in studying sentences outside the realm of literary fiction. Read popular nonfiction. Read children’s books. Heck, read cereal boxes.

那些只想写得更清楚简洁的人可能会发现在文学小说领域之外学习句子会获得更大的好处。 阅读流行的非小说。 阅读儿童读物。 哎呀,看谷物盒。

A good place to find sturdy, workmanlike sentences is in the work of genre novelists, the authors who deal in hardscrabble detectives, spurned lovers, clever lawyers, and dreamy vampires.

体裁小说家,从事顽强侦探的作家,弃的恋人,聪明的律师和梦幻般的吸血鬼,是寻找坚固,熟练的句子的好地方。

Yes, these books are often rife with cliches. But they are never confusing. Authors like James Patterson, Linwood Barclay, and Harlan Coben are experts in making sentences go down easy. I’ve learned plenty from studying their writing — I’m no book snob — and you’ll find some of their sentences in First and Last.

是的,这些书常常充斥着陈词滥调。 但是他们从不混淆。 詹姆斯·帕特森(James Patterson),林伍德·巴克莱(Linwood Barclay)和哈伦·科本(Harlan Coben)之类的专家都是使句子变得容易的专家。 通过研究他们的写作,我学到了很多东西-我不是书本势利的人-您会在First和Last中找到他们的一些句子。

“If it sounds like writing, I rewrite it.”
“如果听起来像是写作,我会重写它。”
— 10 rules of writing, Elmore Leonard
— 10条写作规则,艾尔莫·伦纳德

The sentences in commercial fiction are spare and straightforward. They contain few flourishes, no hooptedoodle. People bring these books on beach vacations for a reason. You can read them while half-drunk and not miss anything.

商业小说中的句子是多余而直接的。 他们几乎没有兴盛,没有胡闹 。 人们将这些书带到海滩度假是有原因的。 您可以半醉时阅读它们,不会错过任何东西。

It is ill-advised, on the other hand, to tackle Ulysses after your fifth Bahama Mama.

另一方面,在您的第五任巴哈马妈妈之后对付尤利西斯是不明智的。

信息不足 (Not enough info)

My main technical goal in making First and Last was simple: grab data from the browser, stick it in a database, then get it back to the browser to display. That’s pretty much it. I wanted to learn how information moves between the front end (Angular) and the back end (Node and MongoDB).

我制作First和Last的主要技术目标很简单:从浏览器中获取数据,将其粘贴到数据库中,然后再将其返回给浏览器进行显示。 就是这样。 我想学习信息如何在前端(角度)和后端(Node和MongoDB)之间移动。

In other words, I wanted to make an app that performed the four basic database operations — create, read, update and delete (CRUD). I’m no fan of acronyms, but I must admit, I like CRUD and MEAN. Them’s sweet words to this surly pessimist.

换句话说,我想开发一个执行四种基本数据库操作的应用程序-创建,读取,更新和删除(CRUD)。 我不喜欢首字母缩写词,但我必须承认,我喜欢CRUD和MEAN。 他们对这位谦卑的悲观主义者的话很甜美。

第1步:获取用户输入 (Step 1: Get user input)
第2步:存储在MongoDB中 (Step 2: Store in MongoDB)
第3步:从数据库中获取并显示在浏览器中 (Step 3: Fetch from database and display in browser)

Like I said, simple. No fancy algorithms. No data visualization. Just moving information, mostly text, back and forth. Still, I made one silly assumption that caused me some trouble.

就像我说的那样,很简单。 没有花哨的算法。 没有数据可视化。 只是来回移动信息,主要是文本。 尽管如此,我还是做出了一个愚蠢的假设,给我带来了一些麻烦。

To display my stored sentences in the browser, I first had to fetch them from the database. When I asked MongoDB for three random entries, it returned an array with three objects. In Angular, I assigned the fetched data to a local array called “sentences,” which I declared as containing objects.

为了在浏览器中显示我存储的句子,我首先必须从数据库中获取它们。 当我向MongoDB请求三个随机条目时,它返回了一个包含三个对象的数组。 在Angular中,我将获取的数据分配给称为“句子”的本地数组,该数组声明为包含对象。

export class DisplayallComponent implements OnInit {  
  sentences: [Object];

That worked fine. Later, I decided to allow users to “like” and comment on sentences. So I had to update, in the back end, the data schema that told MongoDB what type of information to store. I declared a like counter as a number and an array of strings called “likedBy,” where I put the usernames of users who had liked a particular pair of sentences.

很好。 后来,我决定允许用户“喜欢”并评论句子。 因此,我不得不在后端更新告诉MongoDB可以存储什么类型信息的数据模式。 我声明了一个like计数器为一个数字和一个名为“ likedBy”的字符串数组,在其中放置了喜欢特定句子对的用户的用户名。

const SentenceSchema = mongoose.Schema({  
  likes: {  
    type: Number, default: 0 
  }, 
  likedBy: {  
    type: [String] 
  }

Again, no problems. Finally, I added comments. Each comment object would contain a username and the body of the comment. I added an array of objects to my data schema, declaring it the same way I had done for my “sentences” array in Angular.

再次,没有问题。 最后,我添加了评论。 每个评论对象将包含一个用户名和评论正文。 我在数据架构中添加了一个对象数组,并以与在Angular中“句子”数组相同的方式声明了它。

const SentenceSchema = mongoose.Schema({  
  likes: {  
    type: Number, default: 0 
  }, 
  likedBy: {  
    type: [String] 
  },
  comments: {
    type: [Object]
  }

When I tested commenting, though, it didn’t work. There were no obvious errors on the front end, no red text screaming at me in the console of Chrome DevTools. When I peeked in the database, however, the comments I had submitted in the browser were nowhere to be found.

但是,当我测试评论时,它不起作用。 在Chrome DevTools的控制台中,前端没有明显的错误,也没有红色文字向我尖叫。 但是,当我浏览数据库时,找不到在浏览器中提交的注释。

After a bit of try-this-try-that and some quiet late-night cursing, I figured out the problem. MongoDB, it turned out, wanted me to be more specific than Angular. I had to tell it the data types of each element in a comment object in my “comments” array. Just stating that the array contained objects wasn’t good enough.

经过一番尝试,然后进行了一些安静的深夜诅咒,我发现了问题所在。 事实证明,MongoDB希望我比Angular更具体。 我必须在“ comments”数组中告诉它注释对象中每个元素的数据类型。 仅说明数组包含对象是不够的。

comments: [{
       username: String,
       body: String
 }],

Programmers, it would seem, have at least one thing in common with the author of Fifty Shades of Grey. Sometimes it pays to be more explicit.

程序员似乎与《 五十度阴影》的作者至少有一点共同点。 有时需要更加明确。

保持简短(ish) (Keep it short(ish))

I love a good long sentence, I really do. Garrison Keillor, of A Prairie Home Companion fame, writes beautiful, funny, rambling sentences that end only when the ink runs out. Novelist E.L. Doctorow starts Billy Bathgate with a 131-word sentence and ends with a 277-word whopper. In A Writer’s Life, nonfiction legend Gay Talese has a sentence that is FOUR HUNDRED AND NINETEEN words long.

我真的很喜欢长句子。 拥有“草原家庭之友”声望的加里森·基洛尔(Garrison Keillor)写的优美,有趣,漫无目的的句子只有在墨水用完时才结束。 小说家EL Doctorow以比利·巴斯盖特 ( Billy Bathgate)开头的131个单词的句子开始,以277个单词的whopper结尾。 在《作家的生活》中 ,非小说类传奇人物盖尔·塔莱斯(Gay Talese)的句子长四百到九十个单词。

But make no mistake — these writers are showing off. They are good at what they do and want you to know it. And that’s fine by me. Because in the hands of a great writer, any sentence, even one longer than Shaquille O’Neal’s Burger King receipt, will be under control.

但是请不要误会-这些作家在炫耀。 他们擅长于做什么,并希望您知道。 我也很好。 因为在一个伟大的作家手中,任何句子,甚至比Shaquille O'Neal的Burger King收据更长的句子,都将得到控制。

I’m no Gay Talese. Neither are you. If you go long, you will go wrong. Trust me. I edit the writing of freelance journalists and academics, and when the clauses start to pile up, so do the problems. Dangling modifiers. Mismatched pronouns. Inelegant repetition. Unnecessary words. Funky conjunctions.

我不是Gay Talese。 你也不是。 如果你走多长时间,那你就会出错。 相信我。 我编辑自由记者和学者的著作,当这些条款开始堆积起来时,问题也随之而来。 悬空修改器。 代词不匹配。 不雅的重复。 不必要的话。 时髦的连词。

In short, blerg.

简而言之, blerg

It is best to vary the length of your sentences — it’s more pleasing to the ear — but keep them in check. A mixture of short and medium-length sentences is your safest bet.

最好更改句子的长度-听起来更令人耳目一新-但请务必加以控制。 中短句子的混合是最安全的选择。

信息太多 (Too much info)

I’m about to share more code, and things are going to get ugly. Sorry, I’m new to this. If you would like to mock me in the comments, feel free.

我将分享更多的代码,事情将变得丑陋。 抱歉,我是新来的。 如果您想在评论中嘲笑我,请放心。

Journalists have thick skin. We need it. Earlier this week, for example, I received the following email — from some guy who rents luxury apartments in Budapest — about an article on intermittent fasting I wrote in 2013.

记者的皮肤很厚。 我们需要。 例如,本周早些时候,我收到了一封电子邮件,该邮件来自某位在布达佩斯租用豪华公寓的人,该邮件涉及我2013年撰写的有关间歇性禁食的文章

Anyway, this was the function called in Angular when a user clicked on the thumbs-up icon under an entry in First and Last, as I originally wrote it.

无论如何,这是当用户单击“我”最初编写的“第一”和“最后一个”条目下的大拇指图标时在Angular中调用的函数。

if(this.authService.loggedIn()) {
  const isInArray = sentence.likedBy.includes(this.username); 
  if(!isInArray) {
    sentence.likedBy.push(this.username); 
    this.authService.incrementLikes(sentence).subscribe(data => {
      this.sentences[index] = data;

Users could “like” a pair of sentences only if they were logged in and hadn’t already “liked” that entry. When those conditions were met, a local array of the users who had liked that pair of sentences was updated.

仅当用户登录并且尚未“喜欢”该条目时,用户才能“喜欢”一对句子。 满足这些条件后,就会更新一个本地数组,其中包括喜欢这对句子的用户。

Then a call was made to update the like counter and “likedBy” array in the database. The entire sentence object was sent to the back end and, when the updated sentence object was returned, the like counter displayed in the browser increased by one.

然后调用了更新数据库中的like计数器和“ likedBy”数组。 整个句子对象被发送到后端,当返回更新的句子对象时,浏览器中显示的类似计数器增加了一个。

In my data model in the back end, I had this, sadly.

不幸的是,在后端的数据模型中,我有这个。

module.exports.incrementLikes = function(sentence, callback) {
  const query = {_id:sentence._id};
  sentence.likes++;
  const likesPlus = sentence.likes;
  const likesUserArray = sentence.likedBy;
  const newLikeUser = likesUserArray[likesUserArray.length - 1];
  Sentences.findOneAndUpdate(query, 
    {likes: likesPlus, $push:{likedBy: newLikeUser}}, 
    {new: true}, callback
  );
}

This function incremented the counter passed in as a parameter and assigned it to a local variable, which replaced the like counter in the database.

此函数递增作为参数传入的计数器,并将其分配给局部变量,该局部变量替换数据库中的类似计数器。

If that weren’t round-a-bout enough, I copied the entire “likedBy” array from the sentence object passed to the function, then made ANOTHER local variable to hold the last username in that array before, finally, pushing that username into the database’s “likedBy” array.

如果还不够,我从传递给函数的句子对象中复制整个“ likedBy”数组,然后使另一个本地变量保存该数组中的最后一个用户名,最后,将该用户名压入数据库的“ likedBy”数组。

It worked, but still. Ridiculous.

它有效,但仍然有效。 荒谬。

The only information MongoDB needed from Angular was the unique ID of the sentence object to update and the username of the user who clicked the thumbs-up icon. Not the whole sentence object.

MongoDB唯一需要Angular提供的信息是要更新的句子对象的唯一ID,以及单击大拇指图标的用户名。 不是整个句子的对象。

So, instead, I created a new object with only those two elements in Angular to pass to the back-end.

因此,我创建了一个只有Angular中只有这两个元素才能传递到后端的新对象。

onLikeClick(sentence, index) {
  if(this.authService.loggedIn()) {
    const isInArray = sentence.likedBy.includes(this.username); 
    if(!isInArray) {
      const updateLikes = {
        likeID: sentence._id,
        likeUsername: this.username
      }
      this.authService.incrementLikes(updateLikes).subscribe(data =>
          this.sentences[index] = data;

Then I simply incremented the like counter inside the database (rather than incrementing outside and overwriting the database value) and pushed the username passed to the function into the database’s “likedBy” array.

然后,我只是简单地在数据库内部增加了like计数器(而不是在外部增加并覆盖了数据库值),然后将传递给函数的用户名推送到数据库的“ likedBy”数组中。

module.exports.incrementLikes = function(updateLikes, callback) {
  const query = {_id:updateLikes.likeID};
  const newLikeUser = updateLikes.likeUsername;
  Sentences.findOneAndUpdate(query, 
    {$inc: {likes: 1}, $push: {likedBy: newLikeUser}}, 
    {new: true}, callback
  );
}

When you’re a newbie to programming, the joy of making something work can cloud judgment. It’s tempting to leave ugly code alone because, after all, it does what I want it to do. But if I value concision when I write prose, why should it be any different when I write code? Clutter is clutter.

当您是编程的新手时,使某项工作正常进行的乐趣可能会影响判断。 将丑陋的代码留在外面很诱人,因为毕竟它能满足我的要求。 但是,如果我在撰写散文时重视简洁,那么为什么在编写代码时又有什么不同呢? 杂乱无章。

No point in passing around information that isn’t required.

没有必要传递不必要的信息。

When a police officer asks for your driver’s license, you don’t also hand over your library card, birth certificate and Ashley Madison password.

当警察要求您提供驾驶执照时,您也不会交出您的借书证,出生证和阿什利·麦迪逊密码。

把事情简单化 (Keep it simple)

I’m a huge fan of readability. I think when you glance at a dense paragraph of long sentences — riddled with acronyms or statistics or symbols or puffy job titles or long, awful words ending in “-ization” — your brain sighs.

我是可读性的忠实拥护者。 我认为,当您浏览一长串密集的长句子时,到处都是首字母缩写词,统计数据或符号,浮肿的工作标题或以“-化”结尾的长而可怕的单词,您的大脑就会叹息。

“Oh, how wonderful,” it moans with its wee brain-mouth. “This is gonna be hella fun.”

“哦,太好了,”它微弱的脑口抱怨着。 “这会很有趣。”

Many people who write occasionally as part of their jobs, academics and subject experts in particular, are so concerned with content that they often fail to consider presentation. They want to be comprehensive, to make all their points — point A to point Z — and will stuff as much information as possible into every sentence.

许多偶尔写工作的人,特别是学者,尤其是学科专家,对内容如此关注,以至于他们常常不考虑演讲。 他们想要变得全面,将所有观点(从A到Z的观点)表达出来,并在每个句子中填充尽可能多的信息。

But if the end result is unreadable and unlikely to be retained, perhaps there’s no point at all. I’d prefer readers to remember a few ideas presented clearly than instantly forget a dozen over-stuffed ideas presented haphazardly.

但是,如果最终结果不可读并且不太可能保留,那么可能根本没有意义。 我希望读者记住清晰呈现的一些想法,而不是立即忘记随意提出的十二个过度填充的想法。

“Poor Faulkner. Does he really think big emotions come from big words? He thinks I don’t know the ten-dollar words. I know them all right. But there are older and simpler and better words, and those are the ones I use.”
“可怜的福克纳。 他真的认为大情绪来自大话吗? 他认为我不知道十美元的字眼。 我知道他们没事。 但是有更老,更简单,更好的单词,这些都是我使用的。”
— Ernest Hemingway
- 海明威

There will always be unsightly clutter in some forms of writing — it’s unavoidable. Articles on programming and technology will have acronyms. Business writing will have buzzwords. Summaries of medical research may contain adjusted rate ratios of 0.86, 96% CI 0.4–0.56.

在某些形式的写作中总会有难看的杂物-这是不可避免的。 有关编程和技术的文章将使用缩写词。 商业写作将成为流行语。 医学研究摘要可包含0.86、96%CI 0.4-0.56的调整比率。

Still, we can try to do better. We can present only the information the reader needs, nothing more. We can resist the urge to impress, to show off our Google-enhanced vocabularies. We can trim decorative adjectives, eschew jargon, avoid “whom” at all costs. We can do more than just dump words on a page.

不过,我们可以尝试做得更好。 我们只能提供读者需要的信息,仅此而已。 我们可以抵制留下深刻印象的冲动,以炫耀Google增强的词汇量。 我们可以修剪装饰形容词,避免行话,不惜一切代价避免使用“ whom”。 我们不仅可以在页面上转储单词,还可以做更多的事情。

Writing well is difficult. But it is the writer who should suffer. Not the reader.

写好很难。 但是作家应该受苦。 不是读者。

翻译自: https://www.freecodecamp.org/news/write-better-sentences-and-do-javascript-crud-with-mean-while-mostly-avoiding-acronyms-fe17905bcec5/

匹配一个字符串的开头和结尾

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值